9

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.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Dave
  • 307
  • 4
  • 15
  • 2
    There seems to be some confusion as to what you're trying to achieve - a Firefox **Add-on**, or a Firefox WebExtension? – Xan Jul 01 '16 at 10:36

1 Answers1

9

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!"}, "*");
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Shweta Matkar
  • 301
  • 1
  • 11
  • All I'm getting with that code is : ReferenceError - chrome is not defined : chrome.runtime.sendMessage(ChromeExtId, {hello: 1}); – Dave Jul 01 '16 at 06:03
  • Please share your manifest file.you can use browser.runtime.sendMessage instead of chrome.runtime.sendMessage in firefox – Shweta Matkar Jul 01 '16 at 06:33
  • Downvoting - you don't understand [how external communication works](https://developer.chrome.com/extensions/messaging#external-webpage). – Xan Jul 01 '16 at 10:37
  • 2
    Now that's actually a correct answer. Though I'd [use custom events](http://stackoverflow.com/a/25847017/934239). – Xan Jul 01 '16 at 13:38