How to fetch URL of current Tab in my chrome extension using javascript

Using javascript, it will work if you are not using it in popup because javascript in popup will return url of popup therefore, in popup, you have to use Chrome tab API and set permission in Chrome manifest.

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

So best way is to use Chrome tab API


You need to be careful with what you mean by "current tab". If the user has more than one window open, each of them with multiple tabs, Chrome defines the "current window" as the one that is running the content script that makes use of the chrome.tabs API. That happened to me and I solved it by referencing not the "current" window but the last focused one:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
});

References:

https://developer.chrome.com/extensions/windows#current-window https://developer.chrome.com/extensions/tabs#method-query

Hope it helps!


Note you must have the tabs permission set in your manifest file

"permissions": [
    "tabs"
],

http://developer.chrome.com/extensions/tabs.html

or the activeTab permission if initiated by a click on the extension button[Xan]

https://developer.chrome.com/extensions/activeTab


Code:

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

Update : If you are on manifest version 3 then proceed with the following,

 async function getCurrentTab() {
 let queryOptions = { active: true, currentWindow: true };

  let [tab] = await browser.tabs.query(queryOptions);
  localStorage.setItem('tabname' , tab);
   return tab;
  }

 getCurrentTab()
 .then((data) => { console.log('newdata',data)})
 .then(() => { console.log('error')});