gpt4 book ai didi

javascript - 无法从循环外访问数组 firefox addon sdk

转载 作者:行者123 更新时间:2023-11-30 17:19:21 26 4
gpt4 key购买 nike

我是 firefox sdk 的新手,在谷歌上学习我试图从数组中的每个循环中推送字符串并稍后读取它但数组仍然是空的。

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:你好:所有网址:它是空的,在循环结束前被打印出来

最佳答案

看起来您需要使用事件系统在内容脚本和附加组件之间进行通信。在此处阅读“与附加组件通信”部分: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts

from their docs

我认为你的代码变成(未经测试):

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

关于javascript - 无法从循环外访问数组 firefox addon sdk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25450155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com