6

我是 Firefox 插件开发的新手。

我需要一种从 Firefox 插件中的 main.js 调用 contentscript 函数的方法。

我在每个打开的网页上都注入了 contentscript xyz.js。

我想从我的 main.js 调用我的 contentscript xyz.js 中存在的函数 abc() 点击我在导航工具栏中放置的按钮。

下面是我的代码。

主.js

..
function addToolbarButton() {
    var document = mediator.getMostRecentWindow('navigator:browser').document;        
    var navBar = document.getElementById('nav-bar');
    if (!navBar) {
        return;
    }
    var btn = document.createElement('toolbarbutton');  
    btn.setAttribute('id', 'mybutton-id');
    btn.setAttribute('type', 'button');
    btn.setAttribute('class', 'toolbarbutton-1');
    btn.setAttribute('image', data.url('icon_16.png'));
    btn.setAttribute('orient', 'vertical');
        btn.setAttribute('label', 'Test');
        btn.addEventListener('click', function() {
            tabs.activeTab.attach({
            //

                abc()     //here i want to call the function present in my contentscript 

            //
        });
        }, false)
    navBar.appendChild(btn);
}

..

xyz.js

..

function abc(){
//here is my code logic
}

..

我开始知道消息传递是这样做的方法,但无法在 Firefox 中实现。

请帮助我,我被困住了。

4

2 回答 2

4

您不能直接调用该函数,您需要向内容脚本发送消息。意思是这样的:

var worker = tabs.activeTab.attach({
  ...
});

// Some time later
worker.postMessage("doABC");

在内容脚本中:

self.on("message", function(message) {
  if (message == "doABC")
    abc();
});

有关与内容脚本通信的更多信息,请参阅文档

于 2012-10-04T07:35:24.320 回答
1

根据文档,它应该以这种方式工作;

但是,我有类似的问题 尚未解决从 ActionButton 访问预加载的内容脚本。

// main.js
function handleClick(state) {
    var myWorker = tabs.activeTab.attach({

    });   
    myWorker.port.emit("initialize", "Message from the add-on");
}

// content.js
/*BEGIN Listen events coming from Add-on script*/
self.port.on("initialize", function () {
    alert('self.port.on("initialize")');
    return;   
});
于 2014-08-12T21:23:10.233 回答