Firefox Addon - Send a message from a web page to a background script

I am trying to convert a Chrome extension to a FireFox addon. The only problem I am facing right now is the link between my webpage in the background of the script.

In Chrome, this is what I did:

background.js

chrome.runtime.onMessageExternal.addListener(function(request)
{
    if (request.hello) { console.log('hello received'); }
});

web pages

chrome.runtime.sendMessage(ChromeExtId, {hello: 1});

I saw that onMessageExternal is not yet supported in FireFox, so I completely lost how to deal with this situation now.

Any help would be greatly appreciated.

+4
source share
1 answer

You can communicate with background.js from a web page via content script. Try the following:

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.hello) {
            console.log('hello received');
        }
    });

content script

var port = chrome.runtime.connect();

window.addEventListener("message", function(event) {

    if (event.source != window)
        return;

    if (event.data.type && (event.data.type == "FROM_PAGE")) {
        console.log("Content script received: " + event.data.text);
        chrome.runtime.sendMessage({
            hello: 1
        });
    }
}, false);

web pages

window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
+3
source

All Articles