我是firefox sdk的新手,在google上学习 我试图从数组中的每个循环推送字符串并稍后读取它 但阵列仍然是空的。
require("sdk/ui/button/action").ActionButton({
id: "list-tabs",
label: "List Tabs",
icon: "./32.png",
onClick: CollectURLs
});
function CollectURLs(){
var tabs = require("sdk/tabs");
var links = [];
for each (var tab in tabs){
if(tab.url.indexOf('google.com') != '-1'){
tab.attach({
contentScript: 'for (var i = 0; i < document.getElementsByTagName("h3").length ; i= i+1){'+
'self.postMessage(document.getElementsByTagName("h3")[i].getElementsByTagName("a")[0].getAttribute(\'href\'));'+
'}',
onMessage: function(message) {
console.log("URL: "+message);
links.push(message);
}
});
}
}
console.log("ALL URLS:"+links);
}
输出:
C:\addon-sdk\bin\hello>cfx run
Using binary at 'C:\Program Files (x86)\Mozilla Firefox\firefox.exe'.
Using profile at 'c:\users\admin\appdata\local\temp\tmpp62fgl.mozrunner'.
JavaScript error: chrome://browser/content/urlbarBindings.xml, line 674: aUrl is undefined
console.log: hello: ALL URLS:
console.log: hello: URL: http://www.aa.com/
console.log: hello: URL: http://www.aa.org/
console.log: hello: URL: http://www.aaschool.ac.uk/
console.log: hello: URL: http://www.theaa.com/route-planner/
console.log: hello: URL: http://www.theaa.com/
console.log: hello: URL: http://www.aa.co.nz/
console.log: hello: URL: http://www.theaa.ie/
console.log: hello: URL: http://finance.yahoo.com/q?s=AA
console.log: hello: URL: http://www.alcoholics-anonymous.org.uk/
console.log: hello: URL: http://en.wikipedia.org/wiki/AA
并且有这个数组 console.log:你好:所有URL: 它是空的,并在循环结束前打印出来
答案 0 :(得分:2)
看起来您需要使用事件系统在内容脚本和附加组件之间进行通信。阅读&#39;与附加组件进行通信&#39;部分在这里: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts
我认为您的代码变为(未经测试):
require("sdk/ui/button/action").ActionButton({
id: "list-tabs",
label: "List Tabs",
icon: "./32.png",
onClick: CollectURLs
});
//moved these out of the method
var tabs = require("sdk/tabs");
var self = require("sdk/self");
function CollectURLs(){
var links = [];
for each (var tab in tabs){
if(tab.url.indexOf('google.com') != '-1'){
worker = tab.attach({ //change here
contentScript: 'for (var i = 0; i < document.getElementsByTagName("h3").length ; i= i+1){'+
'self.postMessage(document.getElementsByTagName("h3")[i].getElementsByTagName("a")[0].getAttribute(\'href\'));'+
'}',
onMessage: function(message) {
//console.log("URL: "+message);
//links.push(message);
self.port.emit("url", message); //change here
}
});
//change here
worker.on("url", function(message) {
links.push(message);
console.log('current link list: ', links);
});
}
}
console.log("empty array expected because the event emitting is async:" + links);
}