1

In the following snippet the alert tells me that "taburl" is undefined. Is there any way of accessing the query result outside of the callback function?

  var taburl;
  chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    taburl = tabs[0].url;
  });
  alert(taburl);
user2817012
  • 261
  • 2
  • 11

1 Answers1

2

The way that you are approaching this problem is incorrect because chrome.tabs.query is an asynchronous method. Read this excellent answer for an explanation of what that entails, as well as a possible solution

EDIT:

Depending on how your project is structured, the simplest solution is to wrap the logic that requires the tab info in a function. Then you can invoke that function from within the chrome.tabs.query callback and pass the tab info in. For example:

var alertTab = function(tab) { alert(tab); }
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
  alertTab(tabs[0].url);
});

This is a very naive/dangerous approach and will only work if you wrap all of the synchronous code dependent on the tab info in that (or other) functions. There are many better approaches that are less bug prone... check out the promise pattern, for example.

Community
  • 1
  • 1
berrberr
  • 1,914
  • 11
  • 16
  • I edited in a basic example to show one way to access that info outside of the callback. (Better than using `setTimeout` :P, but there are other better solutions as well - it all depends on how your code is structured) – berrberr Jul 18 '14 at 14:28