简体   繁体   English

如何从firefox插件中的main.js调用内容脚本函数

[英]How to call a content script function from main.js in firefox addon

I am new to Firefox addon development. 我是Firefox插件开发的新手。

I need a way to call a contentscript function from main.js in firefox addon. 我需要一种方法从firefox插件中的main.js调用contentcript函数。

I have injected contentscript xyz.js on every opening webpage. 我在每个开放的网页上都注入了contentcript xyz.js。

I want to call function abc() present in my contentscript xyz.js from my main.js on click of a button which i have place in navigation toolbar. 我想从我的main.js中调用我的脚本xyz.js中的函数abc(),点击我在导航工具栏中的一个按钮。

Below is my code. 以下是我的代码。

Main.js Main.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 xyz.js

..

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

..

I came to know that message passing is way to do so but unable to implement in firefox. 我开始知道消息传递是这样做但无法在Firefox中实现。

Please help me i have got stuckd. 请帮帮我,我被困了。

You cannot call the function directly, you need to send a message to the content script. 您无法直接调用该函数,您需要向内容脚本发送消息。 Meaning something like that: 意思是这样的:

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

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

And in the content script: 并在内容脚本中:

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

For more information on communicating with content scripts see documentation . 有关与内容脚本通信的更多信息,请参阅文档

According to documentation it should work this way; 根据文件,它应该这样工作;

However I have similar question Accessing pre-loaded content script from ActionButton not yet resolved. 但是我有类似的问题从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;   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM