0

this works fine

var tabUrl;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    tabUrl = tabs[0].url;
    console.log(tabUrl);
});

but this show undefined

var tabUrl;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    tabUrl = tabs[0].url;
});

console.log(tabUrl);

However I want to check URL to change my popup.html according to the page that user is browsing but I don't want to do this all inside chrome.tabs.query function

Chocospy
  • 1
  • 3

1 Answers1

0

According to W3's specification of how Javascript variables scope work. In order to access variables inside a function, you must not add the var sign before, and use window.Variable to access it.

This should work:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

tabUrl = tabs[0].url;
});


console.log(window.tabUrl);
Mike B
  • 145
  • 5
  • `chrome.tabs.query` works asynchronously. The variable `window.tabUrl` will still be undefined because it is accessed before the callback function is executed. – Iván Nokonoko Jun 14 '16 at 11:50