Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your problem can be simplified to:</p> <pre><code>/*1.*/ var fourmTabs = []; /*2.*/ chrome.tabs.query({}, function(tabs) { /*3.*/ fourmTabs[0] = tabs[0]; /*4.*/ }); /*5.*/ console.log(fourmTabs[0]); </code></pre> <p>You expect that the <code>fourmTabs</code> array is updated (by line 3) when line 5 is reached.<br> That is <strong>wrong</strong>, because the <code>chrome.tabs.query</code> method is <strong>asynchronous</strong>.</p> <hr> <p>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 <strong>and</strong> a story.</p> <pre><code>/*1.*/ var rope = null; /*2.*/ requestRope(function(receivedRope) { /*3.*/ rope = receivedRope; /*4.*/ }); /*5.*/ grab(rope); </code></pre> <ul> <li>At line 1, the presence of a rope is announced. </li> <li>At lines 2-4, a <em>callback function</em> is created, which ought to be called by the <code>requestRope</code> function.</li> <li>At line 5, you're going to grab the rope via the <code>grab</code> function.</li> </ul> <p>When <code>requestRope</code> is implemented <strong>synchronously</strong>, there's no problem:<br> &emsp; You: "Hi, I want a rope. Please <em>throw the rope</em><sup>"call the callback function"</sup> when you've got one."<br> &emsp; She: "Sure." <em>throws rope</em><br> &emsp; You: <em>Jumps and grabs rope</em> - You manage to get at the other side, <em>alive</em>.</p> <p>When <code>requestRope</code> is implemented <strong>asynchronously</strong>, you may have a problem if you treat it as synchronous:<br> &emsp; You: "Please throw a rope at me."<br> &emsp; She: "Sure. Let's have a look..."<br> &emsp; You: <em>Jumps and attempts to grab rope</em> Because there's no rope, you fall and die.<br> &emsp; She: <em>Throws rope</em> <sub>Too late, of course.</sub></p> <hr> <p>Now you've seen the difference between an asynchronously and synchronously implemented function, let's solve your original question:</p> <pre><code>var fourmTabs = new Array(); chrome.tabs.query({}, function (tabs) { for (var i = 0; i &lt; tabs.length; i++) { fourmTabs[i] = tabs[i]; } // Moved code inside the callback handler for (var i = 0; i &lt; fourmTabs.length; i++) { if (fourmTabs[i] != null) window.console.log(fourmTabs[i].url); else { window.console.log("??" + i); } } }); // &lt;moved code inside callback function of chrome.tabs.query&gt; </code></pre> <p>With breakpoints, your code works, because by the time that the second part of the code is reached, the callback has already been called.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload