Communicating with a content script in a Firefox extension

社会主义新天地 提交于 2020-01-14 06:15:08

问题


I have a Chrome extension which does the following action:

chrome.extension.sendRequest({action: "store", working_tab: tab.id, 
                              store_text: text});

And Correspondingly, the listener is:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.action == "store") {
     storeObject.process();
     sendResponse({});
   }
}

Can you please guide me, what would be the corresponding code for a Firefox Extension? I followed the Firefox Extension tutorial but that didn't help me much.

Appreciate, if you could post me a code snippet, so that I could start working on this.

Reason why I'm doing this: I'm trying to port this Chrome extension to Firefox.


回答1:


The equivalent code with the Firefox Add-on SDK would be something like this code:

In the main.js script, a page-mod object is created that injects a content script into a page, and also sends it a message:

// main add-on script
pageMod.PageMod({
  include: "*.org",
  contentScriptFile: self.data.url("my-script.js"),
  // Send the content script a message inside onAttach
  onAttach: function(worker) {
    worker.port.emit("replacePage", "Page matches ruleset");
  }
});

In the content script, the event is received:

// content script
self.port.on("replacePage", function(message) {
  document.body.innerHTML = "<h1>" + message + "</h1>";
});

A working example can be found here:

https://builder.addons.mozilla.org/addon/1053578/latest/

It's important to note that, although the above example only shows communication going from the add-on to the page, the reverse is also possible - you can send messages from the content script back to the add-on using the same basic pattern of sending messages from the worker to the content script and back again. For more on how content script communication works:

https://addons.mozilla.org/en-US/developers/docs/sdk/1.7/dev-guide/guides/content-scripts/index.html



来源:https://stackoverflow.com/questions/11107921/communicating-with-a-content-script-in-a-firefox-extension

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