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
Assuming you have the "tabs" permission listed in your manifest.json, you can get the url of the current 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;
This might also work, depending on which "background" context you're in:
function onGot(tabInfo) {
let url = tabInfo.url; // url is a property from the Tab object, see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/Tab
}
browser.tabs.getCurrent().then(onGot, console.error);
Nonetheless, I advise method 1 for background scripts and method 2 for content scripts.
Source: developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/getCurrent
If you have further questions, feel free to join the #webextensions channel on irc.mozilla.org.