Panel & PageMod Content Script message passing in a Firefox extension

帅比萌擦擦* 提交于 2020-01-02 04:42:08

问题


I'm working on porting a Chrome extension to Firefox using the Firefox Add-on SDK.

The extension consists of a panel hooked up to a toolbar button (equivalent to Chrome's popup.html + browser action) and a PageMod content script.

When the panel opens, it needs to send a message to the current tab's content script to receive an object containing some information from that page. The part I'm having trouble with is how to actually do the message passing. Can someone help point me in the right direction? I can't seem to find many resources to help Chrome extension developers learn Firefox addon development.

The following question demonstrates this concept in the Chrome environment. I just need help porting it to Firefox.
Chrome Extension - Message Passing from Popup to Content Script


回答1:


It's somewhat more complicated with the Add-on SDK because you don't communicate with tabs there - you communicate with workers that you created. And the system won't keep track of the workers, you have to do it yourself. Something like this should work (untested code):

var workers = [];
var pageMod = require("page-mod");
pageMod.PageMod({
  include: ...,
  contentScriptFile: ...,
  onAttach: function(worker)
  {
    workers.push(worker);
    worker.on("detach", function()
    {
      var index = workers.indexOf(worker);
      if (index >= 0)
        workers.splice(index, 1);
    });
  }
});

This makes sure that the workers variable contains the list of active workers (Worker object documentation). So when you need to send a message to the worker assigned to a particular tab you do this:

var tabs = require('tabs');
for (var i = 0; i < workers.length; i++)
  if (workers[i].tab == tabs.activeTab)
    worker.postMessage(...);

Of course you can do this only from the extension itself, not from the content script loaded into a panel or something like that. If you are in a content script you first have to send a message to the extension and it should then forward the message to the worker in the tab.



来源:https://stackoverflow.com/questions/9571894/panel-pagemod-content-script-message-passing-in-a-firefox-extension

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