How to implement message passing in Firefox extension?

有些话、适合烂在心里 提交于 2019-12-04 07:20:15

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