Chrome扩展:查询选项卡异步 [英] Chrome Extension: query tabs async

查看:335
本文介绍了Chrome扩展:查询选项卡异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个变量被设置为函数的返回值,这些功能都得到一个标签的URL,而实际标签对象的引用,并将它们存储在变量。我有一些code:

I have two variables being set to the "return value" of functions, these functions are to get the URL of a tab, and a reference to the actual tab object, and store them in variables. I have some code:

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,但当我从回调外返回标签,它返回正常,因为尽管这是一个同步调用。我有这个现象在调试器截图。我想我最好的学习如何应对铬异步方法,但是这是非常混乱。有人可以解释这种现象给我?

Why is it that, URL is undefined, though I'm returning the URL from within the callback function, yet when I return tab from outside of the callback, it returns fine, as though this were a synchronous call. I have a screenshot of this phenomenon in the debugger. I'm trying my best to learn how to deal with the asynchronous methods in chrome, but this is very confusing. Can someone explain this behavior to me?

推荐答案

正如你已经说 chrome.tabs.query 函数是异步的。正因为如此,你不能依靠收益,相反,你必须使用回调。对于Chrome扩展的文档解释了它相当不错: http://developer.chrome.com /extensions/overview.html#sync-example

As you already said the chrome.tabs.query function is asynchronous. Because of this, you cannot rely on return, instead you have to use callbacks. The documentation for Chrome extension explains it quite well: http://developer.chrome.com/extensions/overview.html#sync-example

所以你的情况,这样的事情可能工作(取决于你想以后做什么用)。

So in your case, something like this might work (depends on what you want to later with it).

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);
}

这篇关于Chrome扩展:查询选项卡异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆