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

Gra*_*and 4 javascript google-chrome-extension

如何获取 MV3 后台 Service Worker 中当前选项卡的 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;
}

Run Code Online (Sandbox Code Playgroud)

现在,服务工作线程正在记录“当前 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
Run Code Online (Sandbox Code Playgroud)

我想这可能和我对promise的了解有限有关!

请帮忙。先感谢您。

Und*_*oen 8

您的功能getTab似乎不正确,您当前正在尝试查询该网址。不在查询选项上。以下功能应该可以工作。

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

还要确保您获得许可tabs

在侦听器中,您也没有使用正确的异步/承诺方法(两个使用Promise.then和 的示例) await

Promise.then

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

await

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

对于“错误:现在无法查询选项卡(用户可能正在拖动选项卡)”。错误,您可以查看此答案,这表明在查询选项卡网址之前有一个小延迟。