0

I'm trying to inject some JS on a web page using a chrome extension. Since I want to enable it only on click and not every time I visit the page, I have the following manifest:

{
  "name": "Assistant",
  "version": "0.1",
  "manifest_version": 2,
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs"
  ],
  "background": {
    "scripts": [
      "js/background.js"
    ],
    "persistent": true
  },
  "content_scripts": [{
        "css": ["css/style.css"],
        "matches": ["http://*/*", "https://*/*"]
  }],
  "browser_action": {
    "default_icon": "icons/icon.png",
    "default_title": "Assistant"
  },
  "web_accessible_resources": ["css/style.css"]
}

In background.js, I load the scripts with this:

chrome.browserAction.onClicked.addListener(function(tab) {

    chrome.tabs.executeScript(null, { file: "js/jquery.min.js" }, function() {
            chrome.tabs.executeScript(null, { file: "js/script.js" });
    });

});

Now on script.js I have the following line:

var a = "testing";
window.b = "testing";
alert("testing");

When I click the button, the browser immediately displays an alert for "testing", meaning it ran the code correctly. But, when I go to the console and try to access a or window.b, both are undefined.

Are these variables being sandboxed somehow? How to make it available for page scripts?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • I think it executes in backgrounds, not in content script. So `window.b` exists in backgrounds enviroment, while `console.log` you call in content enviroment. Try click _inspect views: background.page_ on `chrome://extensions/` page and call `window.b` in that console. It will show "testing". – rie May 01 '17 at 20:15
  • how can I call them in the content environment? – sigmaxf May 05 '17 at 23:02
  • Possible duplicate of [Insert code into the page context using a content script](http://stackoverflow.com/questions/9515704/insert-code-into-the-page-context-using-a-content-script) – Johan Hoeksma May 15 '17 at 05:22
  • Take a look at this: https://gist.github.com/naholyr/8657eb77e198e1b49c1d – Johan Hoeksma May 15 '17 at 05:24

0 Answers0