如何使用 Manifest v3 获取当前选项卡 URL?

How to get current tab URL using Manifest v3?

MV3后台service worker中如何获取当前tab的URL?

这是我的:

let currentURL;

chrome.action.onClicked.addListener(handleBrowserActionClicked);

chrome.commands.onCommand.addListener(function(command) {
  console.log("Command:", command);
  handleBrowserActionClicked();
});

function handleBrowserActionClicked() {
  togglePlugin();
}
function togglePlugin() {
  console.log("toggle plugin");
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { greeting: "activateFeedback" });
  });
}

// Fires when the active tab in a window changes.
chrome.tabs.onActivated.addListener(function () {
    console.log("TAB CHANGED")
    //firstTimeRunning = true
    //feedbackActivated = false
    currentURL = getTab()
    .then(console.log("Current URL: " + currentURL))
})

// Fired when a tab is updated.
chrome.tabs.onUpdated.addListener(function () {
    console.log("TAB UPDATED")
    currentURL = getTab() // line 32
    .then(console.log("Current URL: " + currentURL))
})

async function getTab() {
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(chrome.tabs[0].url); // line 38
  return tab;
}

现在 service worker 正在记录“Current URL: [object Promise]”,而不是例如“https://www.google.com”

它也在控制台中给出错误(行号见上面的注释)

background.js:38 Uncaught (in promise) TypeError: Cannot read property 'url' of undefined
    at getTab (background.js:38)
    at background.js:32

我觉得可能是我对promises的了解有限吧!

请帮忙。 提前谢谢你。

您的函数 getTab 似乎不正确,您目前正试图在 url 上查询。不在查询选项上。以下函数应该可以工作。

async function getTab() {
  let queryOptions = { active: true, currentWindow: true };
  let tabs = await chrome.tabs.query(queryOptions);
  return tabs[0].url;
}

还要确保您拥有 tabs 权限。

在侦听器中,您也没有使用正确的 async/promise 方法,两个示例使用 Promise.thenawait

Promise.then:

chrome.tabs.onUpdated.addListener(function () {
    console.log("TAB UPDATED")
    getTab().then(url => {
        console.log(url);
    })
})

await:

chrome.tabs.onUpdated.addListener(async function () {
    console.log("TAB UPDATED")
    let url = await getTab()
    console.log(url)
})

对于“错误:现在无法查询选项卡(用户可能正在拖动选项卡)”。您可以查看 this answer 的错误,这表明在查询选项卡 url.

之前有一个小的延迟
const tab = (await chrome.tabs.query({ active: true }))[0]

只需在manifest.json

中使用“activeTab”权限

在您的 manifest.json.

添加 activeTab
"permissions": [
    "activeTab",
],

Background.js

chrome.action.onClicked.addListener((tab) => {
 console.log(tab.url);
});

我相信它会帮助您获取当前选项卡URL。 有用的链接 - ActiveTab