javascript - How to Access / Read any Text / Tag Value from the Webpage using Chrome Extension -
i writing first chrome plugin , want text present on current webpage , show alert when click extension. lets using any webpage on www.google.com after search query, google shows "about 1,21,00,00,000 results (0.39 seconds) " . want show text alert when execute plugin. doing.
here manifest.json using
{ "manifest_version": 2, "name": "getting started example", "description": "this extension shows google image search result current page", "version": "1.0", "background": { "persistent": false, "scripts": ["background.js"] }, "content_scripts": [{ "matches": ["*://*.google.com/*"], "js": ["content.js"] }], "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": [ "activetab" ] }
here popup.js
document.addeventlistener('domcontentloaded', function() { document.getelementbyid("checkpage").addeventlistener("click", handler); });` function handler() { var = document.getelementbyid("resultstats"); alert(a.innertext); // or alert(a.innerhtml); }
here content.js
// listen messages chrome.runtime.onmessage.addlistener(function (msg, sender, sendresponse) { // if received message has expected format... if (msg.text === 'report_back') { // call specified callback, passing // web-page's dom content argument sendresponse(document.all[0].outerhtml); } });
here background.js
var urlregex = /^https?:\/\/(?:[^./?#]+\.)?google\.com/; // function use callback function dostuffwithdom(domcontent) { console.log('i received following dom content:\n' + domcontent); } // when browser-action button clicked... chrome.browseraction.onclicked.addlistener(function (tab) { // ...check url of active tab against our pattern and... if (urlregex.test(tab.url)) { // ...if matches, send message specifying callback chrome.tabs.sendmessage(tab.id, {text: 'report_back'}, dostuffwithdom); } });
1) run content scrip after document ready ** check "run_at"
"content_scripts": [{ "run_at": "document_idle", "matches"["*://*.google.com/*"], "js": ["content.js"] }],
2) on click of extension make js run( popup js). popup js has access ( open page document)
// function use callback function dostuffwithdom() { //console.log('i received following dom content:\n' + domcontent); //get tabid when browser action clicked @ tabid = tab.id chrome.tabs.executescript(tabid, {file: "js/popup.js"}); }
3) in popup js simple can set alert
var = document.getelementbyid("resultstats"); alert(a.innertext); // or alert(a.innerhtml);
Comments
Post a Comment