0

Can I get the value of a variable from another script using content script? For example from a script on Facebook. Sorry for my english.

  • 1
    I can't say for sure, but based on the fact that you need to switch contexts or whatever, in the dev tools console, I'd say you can't, they're probably separate environments. – TankorSmash Sep 02 '14 at 16:57
  • I think you can have a content script inject a ` – apsillers Sep 02 '14 at 17:06

1 Answers1

2

Your content script can inject a <script> element into the page. That injected script should read the value and use DOM events to pass the value to the content script.

In your content script:

// inject a script from the extension's files
// into the execution environment of the main page
var s = document.createElement('script');
s.src = chrome.extension.getURL("value _reader.js");
document.documentElement.appendChild(s);

document.addEventListener("valueFromPageEvent", function(event) {
    console.log("the content script just got the value " + event.detail.val);
});

Inside value_reader.js (which we injected in the content script above), assuming we want to the read the variable foobar from the page:

var dataObj = { "val": foobar };
var storeEvent = new CustomEvent('valueFromPageEvent', { "detail": dataObj });
document.dispatchEvent(storeEvent);

N.B.: The value_reader.js script must be in your extension's list of web_accessible_resources in the manifest.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 1
    Note: this method can fail if the page in question has a restrictive CSP. – Xan Sep 02 '14 at 18:18
  • @Xan An important note and an interesting problem. Perhaps you could get around this for specific services by using `webRequest` to alter `.js` files to include your event-emitting code? You'd have to make a tailor-made solution for each service you wanted to hijack, though, specifying which `.js` file to inject and when to fire the event. – apsillers Sep 02 '14 at 18:26