Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 468
Racoon Avatar asked Sep 06 '17 15:09

Racoon


1 Answers

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.

like image 145
Smile4ever Avatar answered Nov 13 '22 04:11

Smile4ever