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

The above code is supposed to assign the URL of current page to variable "currentURL", however, the console log inside the function logs the correct value, while the one outside the function logs "undefined".

I cannot figure out why "currentURL" 's value is undefined outside the function, any help would be greatly appreciated!

Ryan Deng
  • 3
  • 4

3 Answers3

1

The callback is async and that’s why you can’t rely on the outer console.log. The outer log happens before the async callback which is still waiting in the event queue. After outer log happens, the callback is processed and so you can successfully log the tabs value inside that callback only.

Refer this documentation for more insights:- http://developer.chrome.com/extensions/overview.html#sync-example

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
1

The chrome.tabs.query() method is asynchronous. Therefore, the value of currentURL is not yet defined when the last line is run.

Looking into async/await functions should help you code your program to wait for the callback to resolve before it moves on further.

0
     var currentURL; // executed first
      chrome.tabs.query({ active: true, currentWindow: true }// executed second
, function (tabs) { // -> executed fourth
        currentURL = tabs[0].url;
        chrome.tabs.remove(tabs[0].id);
        console.log(currentURL);
      });
      console.log(currentURL);// executed third

Pay attention that the function inside chrome.tabs.query is a callback. That means it will be launched after the console log you wrote outside. That's why the value in your console.log is still undefined

IsraGab
  • 4,819
  • 3
  • 27
  • 46