![](/img/trans.png)
[英]How to call a function in another script from main.js in electron
[英]How to call a content script function from main.js in firefox addon
我是Firefox插件開發的新手。
我需要一種方法從firefox插件中的main.js調用contentcript函數。
我在每個開放的網頁上都注入了contentcript xyz.js。
我想從我的main.js中調用我的腳本xyz.js中的函數abc(),點擊我在導航工具欄中的一個按鈕。
以下是我的代碼。
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
..
function abc(){
//here is my code logic
}
..
我開始知道消息傳遞是這樣做但無法在Firefox中實現。
請幫幫我,我被困了。
您無法直接調用該函數,您需要向內容腳本發送消息。 意思是這樣的:
var worker = tabs.activeTab.attach({
...
});
// Some time later
worker.postMessage("doABC");
並在內容腳本中:
self.on("message", function(message) {
if (message == "doABC")
abc();
});
有關與內容腳本通信的更多信息,請參閱文檔 。
根據文件,它應該這樣工作;
但是我有類似的問題從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.