Tuesday, May 21, 2024
6
rated 0 times [  9] [ 3]  / answers: 1 / hits: 16288  / 11 Years ago, mon, september 9, 2013, 12:00:00

With a content script you can inject a script tag into the DOM in order to access variables in the original page (as explained in this question).



I want to avoid injecting my code into every page and instead only do that when the user clicks on the extension icon.



When I tried using the same code as for the content script the values were undefined, although the script was inserted correctly.



Is this possible? Otherwise is using a content script and communicating with it the preferred solution?



Here is the code I'm using:



var scr = document.createElement(script);
scr.type=text/javascript;
scr.innerHTML = setInterval('console.log(window.testVar)', 1000)
document.body.appendChild(scr)





Manifest excerpt:



 permissions: [
tabs,
http://*/*, https://*/*
],
background: {
scripts: [inject.js]
},

More From » google-chrome-extension

 Answers
37

You can create a new background script with the following code:



chrome.browserAction.onClicked.addListener( function() {
chrome.tabs.executeScript( { file: 'inject.js' } );
});


Your inject.js should stay as part of the extension, but you don't need to mention it in the manifest. This way, it will be run as a content script each time you press the extension icon. You didn't include the part of the manifest where you define the browserAction, but you just need to not specify a default_popup.


[#75804] Sunday, September 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;