I've got this on my contentscript.js:
//some code
self.postMessage(fromDOM);
Now where should I write the receiving code for the message?
self.on("message", function(addonMessage) {
//message handling code
});
The message passed from contenscript must be displayed on the panel which opens when the widget is cilcked.
Now, should I write the receiving code in main.js and from there modify the panel's HTML (call it popup.html)? or send it directly to popup.js (script linked to popup.html)?
If so, how can such message passing can occur? A sample code will help it further.
main.js:
var data = require("sdk/self").data;
var panel = require("sdk/panel").Panel({
width: 212,
height: 200,
contentURL: data.url("panel.html")
});
require("sdk/widget").Widget({
label: "panel",
id: "panel",
contentURL: data.url("icon.png"),
panel:panel
});
var self = require("sdk/self");
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "http://results.griet.in/*",
contentScriptFile: data.url("contentscript.js")
});
pageMod.port.on("data", function (data) {
panel.port.emit("data", data);
});
panel.js:
var total= 0,percentage = 0;
self.port.on("data", function (data) {
// `data` is the same data from the pageMod, serialized
total = data;
percentage = total/7.25;
document.getElementById("total").innerHTML = total;
document.getElementById("percentage").innerHTML = percentage.toFixed(2)+" %";
});
Content scripts can't directly communicate to each other, but they can be managed via your addon code (main.js in this case). Your main.js just forwards messages from the page mod to your panel, pretty much:
// Set up your main.js to communicate back and forth
let pageMod = PageMod(...)
let panel = Panel(...)
pageMod.port.on("data", function (data) {
panel.port.emit("data", data);
});
// Your page-mod script
self.port.emit("data", data);
// Your panel script
self.port.on("data", function (data) {
// `data` is the same data from the pageMod, serialized
});