Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox Addon - Send message from webpage to background script

I'm trying to convert my Chrome extension to a FireFox addon. The only issue I am having now is communicating between my webpage to the background script.

In Chrome, this is what I did:

background.js

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

webpage

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

I saw that onMessageExternal is not supported in FireFox yet, so I'm at a complete loss how to handle this situation now.

Any assistance would be greatly appreciated.

like image 608
Dave Avatar asked Jun 30 '16 20:06

Dave


1 Answers

You can communicate with background.js from webpage through content-script. Try this:

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

webpage

window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
like image 131
Shweta Matkar Avatar answered Oct 31 '22 10:10

Shweta Matkar