Dave
Dave

Reputation: 307

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.

Upvotes: 9

Views: 3163

Answers (1)

Shweta Matkar
Shweta Matkar

Reputation: 301

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!"}, "*");

Upvotes: 9

Related Questions