javascript 调用chrome.tabs.query后,结果不可用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11688171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:00:43  来源:igfitidea点击:

After calling chrome.tabs.query, the results are not available

javascriptasynchronousgoogle-chrome-extensionbreakpointsgoogle-chrome-devtools

提问by samy

I'm creating (learning) an extension for Google Chrome.

我正在为 Google Chrome 创建(学习)一个扩展程序。

To debug some code, I inserted console.log(), as follows:

为了调试一些代码,我插入了console.log(),如下所示:

var fourmTabs = new Array();
chrome.tabs.query({}, function (tabs) {
    for (var i = 0; i < tabs.length; i++) {
        fourmTabs[i] = tabs[i];
    }
});
for (var i = 0; i < fourmTabs.length; i++) {
    if (fourmTabs[i] != null)
        window.console.log(fourmTabs[i].url);
    else {
        window.console.log("??" + i);
    }
}

It's very simple code: get all tabs info into an array of my own, and print some things.

这是非常简单的代码:将所有选项卡信息放入我自己的数组中,然后打印一些内容。

To check whether the code works as it should, I run the code. Here comes the problem:

为了检查代码是否正常工作,我运行了代码。问题来了:

  • When I use breakpoints (via the Developer tools), the code runs fine.
  • Without breakpoints, nothing is printed.
  • 当我使用断点(通过开发人员工具)时,代码运行良好。
  • 如果没有断点,则不会打印任何内容。

Any idea why?

知道为什么吗?

回答by Rob W

Your problem can be simplified to:

您的问题可以简化为:

/*1.*/ var fourmTabs = [];
/*2.*/ chrome.tabs.query({}, function(tabs) {
/*3.*/     fourmTabs[0] = tabs[0];
/*4.*/ });
/*5.*/ console.log(fourmTabs[0]);

You expect that the fourmTabsarray is updated (by line 3) when line 5 is reached.
That is wrong, because the chrome.tabs.querymethod is asynchronous.

您希望在fourmTabs到达第 5 行时更新数组(按第 3 行)。
这是错误的,因为该chrome.tabs.query方法是异步的



In an attempt to make you understand the significance of the asynchronous aspect, I show a code snippet with the same structure as your code anda story.

为了让您了解异步方面的重要性,我展示了一个与您的代码具有相同结构的代码片段一个故事。

/*1.*/ var rope = null;
/*2.*/ requestRope(function(receivedRope) {
/*3.*/     rope = receivedRope;
/*4.*/ });
/*5.*/ grab(rope);
  • At line 1, the presence of a rope is announced.
  • At lines 2-4, a callback functionis created, which ought to be called by the requestRopefunction.
  • At line 5, you're going to grab the rope via the grabfunction.
  • 在第 1 行,宣布绳子的存在。
  • 在第 2-4 行,创建了一个回调函数,它应该被requestRope函数调用。
  • 在第 5 行,您将通过grab函数抓取绳索。

When requestRopeis implemented synchronously, there's no problem:
  You: "Hi, I want a rope. Please throw the rope"call the callback function"when you've got one."
  She: "Sure." throws rope
  You: Jumps and grabs rope- You manage to get at the other side, alive.

requestRope实现同步,没有任何问题:
  你:“您好,我想绳子请。抛绳‘调用回调函数’,当你有一个。”
  她:“当然。” 扔绳子
  你:跳跃并抓住绳子- 你设法到达另一边,活着

When requestRopeis implemented asynchronously, you may have a problem if you treat it as synchronous:
  You: "Please throw a rope at me."
  She: "Sure. Let's have a look..."
  You: Jumps and attempts to grab ropeBecause there's no rope, you fall and die.
  She: Throws ropeToo late, of course.

requestRope异步实现的,如果你把它当成同步的,你可能会遇到一个问题:
  你:“请向我扔一根绳子。”
  她:“当然。让我们看看……”
  你:跳跃并试图抓住绳子因为没有绳子,你跌倒并死去。
  她:扔绳子当然太晚了。



Now you've seen the difference between an asynchronously and synchronously implemented function, let's solve your original question:

现在您已经看到了异步和同步实现的函数之间的区别,让我们解决您最初的问题:

var fourmTabs = new Array();
chrome.tabs.query({}, function (tabs) {
    for (var i = 0; i < tabs.length; i++) {
        fourmTabs[i] = tabs[i];
    }
    // Moved code inside the callback handler
    for (var i = 0; i < fourmTabs.length; i++) {
        if (fourmTabs[i] != null)
           window.console.log(fourmTabs[i].url);
        else {
            window.console.log("??" + i);
        }
    }
});
// <moved code inside callback function of chrome.tabs.query>

With breakpoints, your code works, because by the time that the second part of the code is reached, the callback has already been called.

使用断点,您的代码可以工作,因为在到达代码的第二部分时,回调已经被调用。