4


I'm writing a Chrome Extension that adds functionality to certain pages a user visits.
To do that, I'll need to inject a few variables and functions that the page needs to be able to call.
These variables/functions are generated in a content script.

However, since content scripts run in a secluded environment, the host page can not access it.

According to this article: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication it is possible for content script and host page to communicate through the DOM by adding events.
But that's a horrible way to do things, and I'd really like to see some way to inject methods/variables easily.

Is there such a possibility?

Thanks!

Svarog
  • 2,188
  • 15
  • 21
  • 3
    [Building a Chrome Extension - Inject code in a page using a Content script](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) is the way to go for injecting variables/functions in a page. However, if you also want to pass the message back to the extension, event handlers cannot be avoided. – Rob W Apr 29 '12 at 15:37

2 Answers2

5

If it still interests anybody, I've found a solution communicating between content script and page itself through messages.

Something like this on the sending script:

window.postMessage({ type: "messageType", params: { param: "value", anotherParam: "value" } }, "*"/*required!*/);

And then on the receiving script do something like this:

window.addEventListener("message", function(event) {
        // We only accept messages from ourselves
        if (event.source != window)
            return;

        switch (event.data.type) {
        case "blabla":
            // do blabla
            // you can use event.data.params to access the parameters sent from page.
            break;
        case "another blabla":
            // do another blabla 
            break;
        }
    });
VAV
  • 1,756
  • 1
  • 16
  • 26
Svarog
  • 2,188
  • 15
  • 21
0

Here's how I coded it on my extension, http://pagexray.com/extension/

on your manifest.json

 "content_scripts": [
    {
        "matches": ["http://*/*"],
        "js": ["script.js"]
    }
],

on your script.js

(function(){
  var script = document.createElement('script');
  script.src = "http://example.com/external.js";
  script.addEventListener('load', function() { });
  document.head.appendChild(script);
})();
fedmich
  • 5,343
  • 3
  • 37
  • 52
  • This doesn't really answer my question. The JS file is inside the extension, not in an http:// url. – Svarog Jul 08 '12 at 12:50