尝试这个:
Main.js[内容脚本]
var workers = [];
var widget = widgets.Widget({
id: "my-link",
label: "my-page",
contentURL: self.data.url('mypage.ico')//,
//emit the click event
contentScript: 'self.port.emit('icon-click', 'icon clicked')'
});
function detachWorker(worker, workerArray) {
var index = workerArray.indexOf(worker);
if(index != -1) {
workerArray.splice(index, 1);
}
}
var pageMod = require('sdk/page-mod').PageMod({
include: ['https://my-page.com'],
//pass the click event to page Script
contentScript: 'self.port.on("icon-click", function()
{document.defaultView.postMessage({ action:"icon-clicked", msg: "my message", "https://my-page.com"})
})',
onAttach: function(worker) {
workers.push(worker);
worker.on('detach', function () {
detachWorker(this, workers);
});
}
});
//pass event to worker's content script
widget.port.on('icon-click', function(){
//use for each on workers
worker[0].port.emit("icon-click", 'icon clicked');
});
现在,在您的页面脚本中收听 postMessage
window.addEventListener('message', function(event) {
//include all the dialog libs/resources/css in page
var data = event.data;
if(data.action === 'icon-clicked'){
showDialog(data.msg);
}
}, false);