我正在开发一个简单的插件,它可以在页面上查找数字并将它们显示在插件的 html 面板中。
您如何访问数据并使用 port.on分配变量?
myMessagePayload 包含"4000, 800"
从 main.js 文件发送的内容。
//main.js
var tag = ".first, .second";
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
//include: "*.example.com",
include: "http://example.com/*",
contentScriptFile: data.url("element-getter.js"),
onAttach: function(worker) {
worker.port.emit("getElements", tag);
worker.port.on("gotElement", function(elementContent) {
pcPanel.port.emit("message",elementContent);
});
}
});
// element-getter.js
self.port.on("getElements", function(tag) {
var elements = document.querySelectorAll(tag);
for (var i = 0; i < elements.length; i++) {
self.port.emit("gotElement", elements[i].innerHTML);
}
});
// display.html
addon.port.on("message", function handleMyMessage(myMessagePayload) {
var firstNumber = parseInt(myMessagePayload[0]);
var secondNumber = parseInt(myMessagePayload[1]);
}
console.log(myMessagePayload);
//info: addon: 4000
//info: addon: 800
console.log(myMessagePayload[0]) //returns 4
console.log(myMessagePayload[1]) //0
console.log(myMessagePayload[2]) //0
console.log(myMessagePayload[3]) //0
如何将 port.on() 接收到的值设置为变量?