2

I'm making a Chrome extension that makes a lot of use of getting the id of the current active tab in the current active window. Using chrome.tabs.query wrapped around a lof of logic makes my code messy, but putting it in it's own function to return the current tab always returns undefined - why?

function _getCurrentTab(){
    var theTab;
    chrome.tabs.query({active:true, currentWindow:true},function(tab){
        theTab = tab;
    });
    return theTab;
};
console.log(_getCurrentTab());

Can anyone help with this?

tripRev
  • 830
  • 3
  • 12
  • 27

1 Answers1

4

chrome.tabs.query is asynchronous, so your return executes before the theTab = tab in the callback or the callback itself is executed, So try:

function _getCurrentTab(callback){ //Take a callback
    var theTab;
    chrome.tabs.query({active:true, currentWindow:true},function(tab){
        callback(tab); //call the callback with argument
    });
};

_displayTab(tab){ //define your callback function
    console.log(tab);
 };

 _getCurrentTab(_displayTab); //invoke the function with the callback function reference
PSL
  • 123,204
  • 21
  • 253
  • 243
  • @tripRev This is the way you handle callbacks, if you are getting undefoned still just put a console.log(tab) inside your chrome.tabs.query callback itself and it will be undefined, because something else is wrong. – PSL Oct 03 '13 at 23:45
  • revisiting this after 3 years I can see you were absolutely correct. If you want a func which returns the current tab, you can't use the result straight away, you need to provide a cbfunc which uses it when it's done. – tripRev Feb 22 '16 at 11:02