在以下代码片段中,警报告诉我“taburl”未定义。有没有办法在回调函数之外访问查询结果?
var taburl;
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
taburl = tabs[0].url;
});
alert(taburl);
最佳答案
您解决此问题的方式不正确,因为 chrome.tabs.query
是一种异步方法。 Read this excellent answer for an explanation of what that entails, as well as a possible solution
编辑:
根据项目的结构,最简单的解决方案是将需要选项卡信息的逻辑包装在一个函数中。然后您可以从 chrome.tabs.query
回调中调用该函数并将选项卡信息传入。例如:
var alertTab = function(tab) { alert(tab); }
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
alertTab(tabs[0].url);
});
这是一种非常幼稚/危险的方法,只有当您将所有依赖于该(或其他)函数中的选项卡信息的同步代码包装起来时才会起作用。有许多更不易出错的更好方法……例如,查看 promise 模式。
关于javascript - 在回调函数范围之外访问来自 chrome.tabs.query 的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24815614/