How to access page variables from Chrome extension background script

Matt Zeunert picture Matt Zeunert · Sep 9, 2013 · Viewed 15k times · Source

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"]
  },

Answer

Krasimir picture Krasimir · Sep 10, 2013

Nope. That's not possible. You may inject a script, but it only have an access to DOM and it could make DOM manipulations. It can not read javascript variables or execute functions in the context of the current page. Your javascript code is run in a sandbox and you are restricted only to the DOM elements.