Firefox WebExtension API: how to get the URL of the active tab? [duplicate]
Asked Answered
F

1

14

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

Frijol answered 6/9, 2017 at 15:59 Comment(0)
W
37

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.

Whalebone answered 6/9, 2017 at 16:21 Comment(6)
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.Aspergillus
@Aspergillus I have edited my answer.Whalebone
@Whalebone how do you retrieve it from the sidebar? I keep getting moz-extensionFielder
browser.tabs.query({currentWindow: true, active: true}) should workWhalebone
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.Tana
@Tana Try adding the permission activeTab to your manifest.jsonWhalebone

© 2022 - 2024 — McMap. All rights reserved.