Inject functions/variables to page from a chrome extension

content-script, google-chrome, google-chrome-extension, javascript

Solution

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;
        }
    });

Problem

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!

Original source

Related problems