0

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

disclaimer: i'm a complete javascript n00b, be gentle.

popup.js:

var foo = '';
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
   function(tabs){
      foo = tabs[0].url;
   }
);

document.getElementById("bar").innerHTML=foo;

This doesn't work as foo is undefined. I know by moving the document.getElementById into the function it works, but the point is I want foo to refer to a variable I can use later on in my popup.js

Community
  • 1
  • 1
Kevin
  • 1,100
  • 1
  • 11
  • 26
  • yep, you're correct rob, thanks! I tried googling around and couldn't find that, thanks so much :) – Kevin Nov 27 '12 at 09:42

1 Answers1

1

I've never used Chrome api... however right off it looks like your issue is basic JavaScript.

You need to be setting your innerHTML of #bar in your callback:

chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
   function(tabs){
      document.getElementById("bar").innerHTML = tabs[0].url;
   }
);

If you don't, here's what happens in the example code you provided:

// 1. Create foo.
var foo = '';

// 2. Call the query function on chrome.tabs
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
   function(tabs){
      // 4. Set foo after query is done doing whatever.
      foo = tabs[0].url;
   }
);

// 3. Set the html of the element with id="bar" to what's in foo (which is empty right now)
document.getElementById("bar").innerHTML=foo;

EDIT: I'm presuming that chrome.tabs.query is an asynchronous call, which is why it has a callback. If it's synchronous, disregard my answer.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232