Reputation: 1711
I have two variables being set to the "return value" of functions, these functions are to get the URL of a tab, and a reference to the actual tab object, and store them in variables. I have some code:
function init(){
var url = getUrl();
var tab = getTab();
}
function getUrl(){
var tablink;
chrome.tabs.query({currentWindow: true, active: true},function(tabs){
tablink = tabs[0].url;
return tablink;
});
}
function getTab(){
var tab;
chrome.tabs.query({currentWindow: true, active: true},function(tabs){
tab = tabs[0];
});
return tab;
}
Why is it that, URL is undefined, though I'm returning the URL from within the callback function, yet when I return tab from outside of the callback, it returns fine, as though this were a synchronous call. I have a screenshot of this phenomenon in the debugger. I'm trying my best to learn how to deal with the asynchronous methods in chrome, but this is very confusing. Can someone explain this behavior to me?
Upvotes: 4
Views: 7284
Reputation: 1525
As you already said the chrome.tabs.query
function is asynchronous. Because of this, you cannot rely on return
, instead you have to use callbacks. The documentation for Chrome extension explains it quite well: http://developer.chrome.com/extensions/overview.html#sync-example
So in your case, something like this might work (depends on what you want to later with it).
var url, tab;
function init(){
chrome.tabs.query({currentWindow: true, active: true},function(tabs){
url = tabs[0].url;
tab = tabs[0];
//Now that we have the data we can proceed and do something with it
processTab();
});
}
function processTab(){
// Use url & tab as you like
console.log(url);
console.log(tab);
}
Upvotes: 7