gpt4 book ai didi

javascript - 将 chrome.tabs.query 放入函数中始终返回 undefined

转载 作者:行者123 更新时间:2023-11-28 20:16:03 27 4
gpt4 key购买 nike

我正在制作一个 Chrome 扩展程序,它大量使用了获取当前事件窗口中当前事件选项卡的 ID。使用 chrome.tabs.query 包裹大量逻辑会使我的代码变得困惑,但将其放入它自己的函数中以返回当前选项卡总是返回未定义 - 为什么?

function _getCurrentTab(){
var theTab;
chrome.tabs.query({active:true, currentWindow:true},function(tab){
theTab = tab;
});
return theTab;
};
console.log(_getCurrentTab());

谁能帮忙解决这个问题吗?

最佳答案

chrome.tabs.query 是异步的,因此您的返回在回调中的 theTab = tab 或回调本身执行之前执行,因此请尝试:

function _getCurrentTab(callback){ //Take a callback
var theTab;
chrome.tabs.query({active:true, currentWindow:true},function(tab){
callback(tab); //call the callback with argument
});
};

_displayTab(tab){ //define your callback function
console.log(tab);
};

_getCurrentTab(_displayTab); //invoke the function with the callback function reference

关于javascript - 将 chrome.tabs.query 放入函数中始终返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19170595/

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