0

I am working on a Chrome extension and the function for the active tab URL is returning an undefined value, although the inner console log is showing the URL

PS: I am a noob in terms of Javascript

function tabURL()
{
  var tabUrl;
  chrome.tabs.query({currentWindow: true,active: true}, function(tabs) {
    tabUrl = tabs[0].url;
    console.log(tabUrl); //Showing the right URL
  });

  console.log(tabUrl); //Showing undefined
   return tabUrl;
}

I expect the activeTab URL but the actual output is undefined

Ceroy
  • 181
  • 2
  • 11
  • 2
    Chrome API is asynchronous so you'll have to rework your code to use callbacks or Promises with async/await (you can simply load Mozilla's WebExtensions polyfill). BTW not related to the issue but you have a typo in the variable name. – wOxxOm Feb 02 '19 at 13:27
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – wOxxOm Feb 02 '19 at 13:28
  • @wOxxOm thanks, I think I have to learn about promises and also I have rectified the typo, it was just in the question. Also, can you suggest any youtube video or an article which covers all these topics – Ceroy Feb 02 '19 at 14:09
  • I don't know which tutorials are good, but AFAIK the easiest approach is to start with async/await syntax, make it work to grasp the concept, then optionally study the underlying mechanism of Promises. – wOxxOm Feb 02 '19 at 14:28
  • @wOxxOm I tried all the approaches using Async and await but wasn't able to get the output. So could you please post an answer to this question to make a function that returns the URL whenever called. Thanks – Ceroy Feb 02 '19 at 19:08
  • I think this is something basic (provided you're using the polyfill I mentioned) that one must tackle oneself so maybe others will post an answer. – wOxxOm Feb 02 '19 at 19:29

0 Answers0