如何直接从面板发送消息到page-mod的内容脚本? [英] How to send message from panel to page-mod's content script directly?

查看:110
本文介绍了如何直接从面板发送消息到page-mod的内容脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果Firefox插件中有一个代码段,如下所示:

If there is a code snippet in Firefox addon like following:

var pagemod = PageMod({
    include: ['*'],
    contentScriptFile: [data.url('content.js')]
});

panel = require("sdk/panel").Panel({
  width: 322,
  height: 427,
  contentURL: data.url("main.html"),
  include:["http://*/*","https://*/*"],
  contentScriptFile: [data.url('panel.js')]  
});

我在Chrome扩展程序中找到了一些示例代码。他们使用 window.parent.postMessage(message,*)发送消息并使用 window.addEventListener(message,function(e) {//做某事} 接收消息。
如何从 panel.js 发送消息到 content.js 直接在Firefox插件中?

I have found some example code in the Chrome extension. They use window.parent.postMessage(message, "*") to send message and use window.addEventListener("message",function (e) {//do something} to receive message. How can I send message from "panel.js" to "content.js" directly in the Firefox addon?

推荐答案

该解决方案的概念非常类似于这个答案

The concept of the solution is very similar to this answer:


  1. 维护每个标签的消息端口列表。

  2. 每当你想发送信息时,都要向所有列出的端口发送信息。

以下代码用于维护端口列表:

The following code is used to maintain a list of ports:

var ports = [];
var pagemod = PageMod({
    include: ['*'],
    contentScriptFile: [data.url('content.js')],
    onAttach: function(worker) {
        ports.push(worker.port);
        worker.on('detach', function() {
            var index = ports.indexOf(worker.port);
            if (index !== -1) ports.splice(index, 1);
        });
    }
});

现在,无论何时你想从 panel.js发送消息,只需使用:

Now, whenever you want to send a message from panel.js, just use:

// panel.js
self.port.emit('message-to-tabs', 'example of message');

创建面板后,必须在主脚本中处理消息:

The message has to be handled in the main script, after creation of the panel:

panel = require('sdk/panel').Panel({
    width: 322,
    height: 427,
    contentURL: data.url('main.html'),
    include: ['http://*/*', 'https://*/*'],
    contentScriptFile: [data.url('panel.js')]  
});
panel.port.on('message-to-tabs', function(message) {
    for (var i=0; i<ports.length; i++) {
        ports[i].emit('message-to-tab', message);
    }
});

在标签的内容脚本(content.js)中,您可以收听此事件并将其处理为如下:

In the tab's content script (content.js), you can listen to this event and handle it as follows:

self.port.on('message-to-tab', function(message) {
    // Do something with message
});

这篇关于如何直接从面板发送消息到page-mod的内容脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆