How to implement message passing in Firefox extension?

冷暖自知 提交于 2019-12-06 03:44:22

问题


I have a file which overwrites overlay.xul that overwrites browser.xul. I want to implement message passing in a similar way as implemented in chrome extensions.

chrome.manifest-

content helloworld content/
overlay chrome://browser/content/browser.xul    chrome://helloworld/content/overlay.xul
overlay chrome://navigator/content/navigator.xul    chrome://helloworld/content/overlay.xul


skin    helloworld  classic/1.0 skin/
style   chrome://global/content/customizeToolbar.xul    chrome://helloworld/content/overlay.css

How to I register content_script.js which in my case is overlay.js?

Overlay.xul -

 <script type="application/x-javascript" src="chrome://helloworld/content/jquery.js" />
 <script type="application/x-javascript" src="chrome://helloworld/content/overlay.js" />
 <script type="application/x-javascript" src="chrome://helloworld/content/background.js" />

Now inside my overlay.js I'm using -

document.documentElement.addEventListener('click', function(e) {

     messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});

}, true);

And the background.js is-

 addMessageListener("MyMessenger.MyMessage", function(obj) {

    Firebug.Console.log(obj.name);
}, true);
  • What is the correct syntax for message passing?
  • How do I configure the connection between content script and browser script?

回答1:


If all you are interested in is really injecting a content script and communicating with it then it should be easier to use the Add-on SDK, particularly the page-mod package. It allows injecting content scripts easily and provides a way to communicate (see "Communicating With Content Scripts" section in the docs I mentioned).

As to messageManager, it is meant for a multi-process environment but it will work in the current single-process Firefox as well. The main problem with your code above is: addMessageListener isn't a global function, you should call messageManager.addMessageListener(). But using messageManager to pass messages between scripts that are loaded into the same namespace and could call each other directly is an overkill anyway.

To communicate with a content script in the current tab the script in the overlay would do:

gBrowser.selectedBrowser.messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});

And the content script would indeed have addMessageListener as a global function so this should work:

addMessageListener("MyMessenger.MyMessage", function(obj) {
  console.log(obj.name);
});


来源:https://stackoverflow.com/questions/8226042/how-to-implement-message-passing-in-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!