13

Working at migrating my old Firefox extension to the up-to-date Webextension format. Earlier, I was able to get the URL of the active tab in the following way:

var URL = tabs.activeTab.url;

Now, it doesn't work. I saw some references for tabs.getCurrent() and tabs.Tab -> url, but didn't find a single example on how to use it. So how I can get the URL of the active Firefox tab and place it into a variable for further usage?

Thanks, Racoon

Racoon
  • 951
  • 3
  • 14
  • 32

1 Answers1

34

Assuming you have the "tabs" permission listed in your manifest.json, you can get the url of the active tab in a background script by using the following:

// verbose variant
function logTabs(tabs) {
    let tab = tabs[0]; // Safe to assume there will only be one result
    console.log(tab.url);
}
  
browser.tabs.query({currentWindow: true, active: true}).then(logTabs, console.error);

// or the short variant
browser.tabs.query({currentWindow: true, active: true}).then((tabs) => {
    let tab = tabs[0]; // Safe to assume there will only be one result
    console.log(tab.url);
}, console.error), 

In a content script, you can get the url by using:

let url = window.location.href;

Don't use browser.tabs.getCurrent because it doesn't return the active tab, but instead the tab where the calling code runs, which may be an inactive tab.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Smile4ever
  • 3,491
  • 2
  • 26
  • 34
  • If you read the documentation page which have linked, it's clear that `tabs.getCurrent()` only works in very limited circumstances. It very specifically states that this does not work in an actual background script. It will only work for scripts which are running in the background context from within a tab, which is relatively uncommon situation. – Makyen Sep 11 '17 at 06:06
  • @Makyen I have edited my answer. – Smile4ever Sep 11 '17 at 10:47
  • @Smile4ever how do you retrieve it from the sidebar? I keep getting `moz-extension` – S. W. G. Mar 26 '22 at 18:23
  • browser.tabs.query({currentWindow: true, active: true}) should work – Smile4ever Mar 28 '22 at 16:56
  • I am also trying to get the URL of active tab. I tried running this script as is and it doesn't work. Any updates or changes on this? Any example I find on Mozilla or google, I always get "ReferenceError: tabs is not defined" --- I have tabs permission in my manifest. It's been quite frustrating because there are no clear answers online :/ this is for a script running in the background btw. – Matt Aug 11 '23 at 20:57
  • @Matt Try adding the permission activeTab to your manifest.json – Smile4ever Sep 01 '23 at 13:46