Александр Александр - 6 months ago 34
jQuery Question

Communication between firefox addon and dev/panel

I need to call high-level API functions when I click on a button in my dev/panel interface. I implemented it this way.
When addon will be onReady state, addon send postMessage to 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
}


The panel will add the received message in the textarea and reply addon just by pressing a certain button:

//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 handles the response. If button "inspect" was pressed, then will be involved the high-level API (namely, PageMod in handleClick function):

//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
////////////////////////////////
});
}
});
}


Q: How can I send postMessage to panel in handleClick () function? Maybe there is a more appropriate way to call a High-Level APIs using dev/panel?

Answer

In index.js declare var _MyPanel;

In onReady:

onReady: function() {
    _MyPanel = this;
    _MyPanel.postMessage("add-on-ready", [panelSide]);
}

And 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]);
            });
        }
    });
}