All the Chrome methods are asynchronous, which means that they just queue up the code to be called later.
Also note that tabs.getSelected
has been deprecated, so I'm using tabs.query({active: true}...
instead.
The callback fires out of order, after everything else has finished:
var currentTab; // 1
chrome.tabs.query({active: true}, // 2, queues up callback and continues
function(tabs) {
currentTab = tabs[0].url; // 4, last, after everything else
});
console.log(currentTab); // 3 callback hasn't fired yet, so undefined
Welcome to what's sometimes called 'callback hell'.
The easiest way around this is to use an asynchronous or promise wrapper library like chrome-extension-async
. This let's you use async
/await
syntax:
async function yourCode() {
try {
const currentTabs = await chrome.tabs.query({active: true});
const currentTab = currentTabs[0];
console.log(currentTab);
}
catch(err) {
// Log errors etc
}
}
You're still making a callback and executing code after it's finished, but now you can easily use variables before and after the await
. I recently blogged about that in a lot more detail than will fit here.