Firefox WebExtension API:如何获取活动选项卡的 URL?

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

正在将我的旧 Firefox 扩展迁移到最新的 Webextension 格式。早些时候,我能够通过以下方式获取活动选项卡的URL:

var URL = tabs.activeTab.url;

现在,它不起作用。我看到了 tabs.getCurrent() 和 tabs.Tab -> url 的一些参考资料,但没有找到有关如何使用它的示例。那么如何获取活动 Firefox 选项卡的 URL 并将其放入变量以供进一步使用?

谢谢, 浣熊

假设您拥有 manifest.json 中列出的“选项卡”权限,您可以使用以下命令在后台脚本中获取活动选项卡的 url:

// 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), 

在内容脚本中,您可以通过以下方式获取 url:

let url = window.location.href;

不要使用 browser.tabs.getCurrent 因为它不 return active 选项卡,而是运行调用代码的选项卡,可能是非活动选项卡。