当我点击开发/面板界面中的按钮时,我需要调用高级API函数。我这样实现了它。 当addon处于onReady状态时,addon将postMessage发送到panelSide。
// index.js
onReady: function() {
// in this function you can communicate
// with the panel document
this.postMessage("add-on-ready", [panelSide]);
//this.postMessage("add-on-ready2", [panelSide]); // This message may be received in logic-panel.js
}
面板将在textarea中添加收到的消息,只需按某个按钮即可回复插件:
//logic-panel.js
window.addEventListener("message", function(event) {
var toAddon = event.ports[0];
toAddon.start();
$(document).ready(function(){
$('#log').append(event.data + '\n');
});
switch(event.data){
case "add-on-ready":
$(document).ready(function(){
$("#inspect").click(function(){
toAddon.postMessage("inspect");
});
$("#exit").click(function(){
toAddon.postMessage("exit");
});
});
break;
default:
toAddon.postMessage("event.data = " + event.data);
alert("event.data = " + event.data);
}
});
Addon处理响应。如果按钮"检查"被按下,然后将涉及高级API(即,在handleClick函数中的PageMod):
//index.js
addonSide.onmessage = function(event) {
console.log(event.data);
switch(event.data){
case "inspect":
console.log("run inspect");
handleClick();
console.log("run inspect end");
break;
case "exit":
console.log("push exit =(");
break;
default:
MyPanel.postMessage("add-on-ready", [panelSide]); //not work
}
}
function handleClick() {
console.log("xpath");
var data = require("sdk/self").data;
var pageMod = require('sdk/page-mod').PageMod({
include: ['*'],
contentScriptFile: data.url("./addonside/xpath.js"),
onAttach: function(worker) {
worker.on('message', function(message) {
console.log('mouseclick: ' + message);
////////////////////////////////
// this.postMessage('mouseclick: ' + message, [panelSide]); // This message not may be received in logic-panel.js
////////////////////////////////
});
}
});
}
问:如何在handleClick()函数中将postMessage发送到面板?也许有一种更合适的方法可以使用dev / panel调用高级API?
答案 0 :(得分:0)
在index.js中声明var _MyPanel;
在onReady
:
onReady: function() {
_MyPanel = this;
_MyPanel.postMessage("add-on-ready", [panelSide]);
}
handleClick()
:
function handleClick() {
console.log("xpath");
var data = require("sdk/self").data;
var pageMod = require('sdk/page-mod').PageMod({
include: ['*'],
contentScriptFile: data.url("./addonside/xpath.js"),
onAttach: function(worker) {
worker.on('message', function(message) {
console.log('mouseclick: ' + message);
_MyPanel.postMessage("mouseclick: " + message, [panelSide]);
});
}
});
}