javascript - 函数在第一次运行时返回 {},然后正常工作
问题描述
我有一个函数可以提供一些 json 数据的内容脚本。它仅在第 2 次以上运行时才能正常工作的问题。不知道如何解决它:(
let links = {};
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.get == "links") {
chrome.tabs.getAllInWindow(null, function (tabs_) {
for (var i = 0; i < tabs_.length; i++) {
if ((tabs_[i]['url'].match(some_var))) {
links[i] = [tabs_[i]['title'],
tabs_[i]['index']
];
}
}
console.log(links);
});
console.log(JSON.stringify(links));
sendResponse({reply: JSON.stringify(links)});
}
});
我第一次运行该函数时,它返回一个空对象 {},然后工作正常。
解决方案
chrome.tabs.getAllInWindow
是异步的 - 所以 在get 有机会做它的事情sendResponse
之前运行......把最后两行放在回调里面 - 像这样function (tabs_)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.get == "links") {
chrome.tabs.getAllInWindow(null, function (tabs_) {
const links = {};
for (var i = 0; i < tabs_.length; i++) {
if ((tabs_[i]['url'].match(some_var))) {
links[i] = [tabs_[i]['title'],
tabs_[i]['index']
];
}
}
console.log(links);
console.log(JSON.stringify(links));
sendResponse({reply: JSON.stringify(links)});
});
return true; // this signifies the response is asynchronous
}
});
推荐阅读
- android - setContentView 是做什么的?
- java - I'm unsure what to put in my try statement and I keep getting an "Ecxeption in thread "main"" error
- python - My global variable isn't found in another function
- bash - Bash replacing white space taking too much time for larger strings
- c++ - 类函数 toString() C++
- c# - Asp.net WebApi 2 使用模型对象上传文件
- java - 如何在不 ping 服务器的情况下检测损坏的客户端套接字
- python - 如何使用owlready2动态创建类和个体?
- python - Python中正确格式化的相关图
- sql - 来自另一个表的列计算