Chrome扩展程序:查询标签异步

时间:2013-11-17 08:57:30

标签: javascript google-chrome asynchronous google-chrome-extension

我有两个变量设置为函数的“返回值”,这些函数用于获取选项卡的URL,以及对实际选项卡对象的引用,并将它们存储在变量中。我有一些代码:

function init(){
    var url = getUrl();
    var tab = getTab();
}

function getUrl(){
    var tablink;
    chrome.tabs.query({currentWindow: true, active: true},function(tabs){
        tablink = tabs[0].url;
        return tablink;
    });

}

function getTab(){
    var tab;
    chrome.tabs.query({currentWindow: true, active: true},function(tabs){
        tab = tabs[0];
    });
    return tab;
}

为什么,URL是未定义的,虽然我从回调函数中返回URL,但是当我从回调函数外部返回tab时,它返回正常,就好像这是同步调用一样。我在调试器中有screenshot这种现象。我正在尽力学习如何处理chrome中的异步方法,但这非常令人困惑。有人可以向我解释这种行为吗?

1 个答案:

答案 0 :(得分:4)

正如您所说,chrome.tabs.query函数是异步的。因此,您不能依赖return,而必须使用回调。 Chrome扩展程序的文档很好地解释了它:http://developer.chrome.com/extensions/overview.html#sync-example

所以在你的情况下,这样的事情可能会起作用(取决于你以后想要的东西)。

var url, tab;
function init(){
    chrome.tabs.query({currentWindow: true, active: true},function(tabs){
       url = tabs[0].url;
       tab = tabs[0];
       //Now that we have the data we can proceed and do something with it
       processTab();
    });
}

function processTab(){
    // Use url & tab as you like
    console.log(url);
    console.log(tab);
}