user2817012
user2817012

Reputation: 261

Accessing the information from chrome.tabs.query outside of the scope of the callback function

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

Upvotes: 1

Views: 453

Answers (1)

berrberr
berrberr

Reputation: 1960

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.

Upvotes: 2

Related Questions