Google chrome extension 全局变量和异步回调函数

Google chrome extension 全局变量和异步回调函数,google-chrome-extension,Google Chrome Extension,如何将当前选项卡的URL存储在变量中,以便以后可以访问它?我用谷歌搜索了一下,但不太了解异步回调函数 var-currentTab getSelected(null,函数(tab){currentTab=tab.url;}) console.log(currentTab)所有Chrome方法都是异步的,这意味着它们只是将稍后调用的代码排队 还要注意的是tabs.getSelected,所以我使用tabs.query({active:true}…) 在所有其他操作完成后,回调将按顺序触发: var

如何将当前选项卡的URL存储在变量中,以便以后可以访问它?我用谷歌搜索了一下,但不太了解异步回调函数

var-currentTab
getSelected(null,函数(tab){currentTab=tab.url;})

console.log(currentTab)

所有Chrome方法都是异步的,这意味着它们只是将稍后调用的代码排队

还要注意的是
tabs.getSelected
,所以我使用
tabs.query({active:true}…

在所有其他操作完成后,回调将按顺序触发:

var currentTab;                   // 1

chrome.tabs.query({active: true}, // 2, queues up callback and continues
    function(tabs) { 
        currentTab = tabs[0].url; // 4, last, after everything else
    });

console.log(currentTab);          // 3 callback hasn't fired yet, so undefined
欢迎来到有时被称为“回调地狱”的地方

解决此问题的最简单方法是使用异步或promise包装库,如。这让您可以使用
async
/
await
语法:

async function yourCode() {
    try {
       const currentTabs = await chrome.tabs.query({active: true});
       const currentTab = currentTabs[0];
       console.log(currentTab);
    }
    catch(err) {
        // Log errors etc
    }
}

您仍然在进行回调并在完成后执行代码,但现在您可以轻松地在
wait
之前和之后使用变量。我最近在Chrome扩展的上下文中解释了异步代码的概念,阅读它并尝试理解类比。啊,好吧,我有点了解现在发生的事情。所以我你没有办法访问在异步函数中设置的变量,即使它是在顶部(全局)声明的?当然不是以你在问题中写的方式。你必须以某种方式延迟对变量的访问,因此在另一个答案中建议的解决方案是最好的选择(另一种方法是使用计时器,例如
setTimeout
,但这会导致不可预测的结果)。