Search code examples
javascriptiframegoogle-chrome-extensiondom-events

Sending message back to Chrome extension from loaded iframe


I have a Chrome extension that users install on their browsers, when you open the extension popup (background page), all it does is loading a whole application back-end running on my server.

What I wanted to do is to have some kind of event emitter on my back-end application that can send message back to the chrome extension that is loaded this application.

I've tried this:

background.html:

<body>
    <iframe id="gateway" src="http://www.catchit.com"></iframe>
</body>

My back-end page for sending messages, say:

www.catchit.com/message/send, which on click runs this:

var event = new CustomEvent(
    "newMessage",
    {
        detail: {
            users: users,
            message: message
        },
        bubbles: true,
        cancelable: false
    }
);

document.dispatchEvent(event);

My content script awaits this event:

document.addEventListener("newMessage", function(data) {
    chrome.runtime.sendMessage(data);
});

My background script as well:

chrome.runtime.onMessage.addListener(function(message) {
    alert("message received" + message);
});

But of course it won't work... Since, the event is fired within iframe context (www.servera.com)

What am I missing here? I can't figure out how to throw a message back. That would be an awesome bridge between real application loaded within extension's popup and extension itself which can later dispatch messages to website opened on user browser.


Solution

  • Based on what gonzalovazzquez said, I've made this solution:

    Background.js:

    // Listen for message from application (iframe)
    top.window.addEventListener("message", function(message) {
        // Notify content-script about new message
    });
    

    My application javascript that is a part of iframe application:

    top.window.postMessage({data: {users: users, message: message}}, "*");
    return false;
    

    From that point, you can tell your content script via background what to do on an actual page/tab, based on message received via application that is loaded within iframe on background.html