You need to enable JavaScript to run this app. 如何在Manifest V3的后台service worker中获取当前标签页URL?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Manifest V3的后台service worker中获取当前标签页URL?

Manifest V3 Service Worker获取当前标签页URL问题修复

错误原因

  • 第38行类型错误:chrome.tabs.query 的入参应为查询配置对象,你错误传入了不存在的 chrome.tabs[0].url。chrome.tabs 是Chrome API的命名空间,不是标签页数组,chrome.tabs[0] 本身为undefined,访问其url属性就触发报错。
  • 打印[object Promise]:async函数默认返回Promise实例,你直接将getTab()的返回值赋值给currentURL,此时拿到的是Promise对象而非异步返回的标签数据;同时then()中直接执行console.log,没有将打印逻辑作为回调函数传入then,导致打印时异步请求还未完成,自然拿不到实际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" });
  });
}

// 标签激活事件监听
chrome.tabs.onActivated.addListener(async function () {
    console.log("TAB CHANGED")
    //firstTimeRunning = true
    //feedbackActivated = false
    const currentTab = await getTab()
    currentURL = currentTab.url
    console.log("Current URL: " + currentURL)
})

// 标签更新事件监听
chrome.tabs.onUpdated.addListener(async function () {
    console.log("TAB UPDATED")
    const currentTab = await getTab()
    currentURL = currentTab.url
    console.log("Current URL: " + currentURL)
})

async function getTab() {
  const queryOptions = { active: true, currentWindow: true };
  // 修复query入参错误
  const [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

补充注意事项

需要在manifest.json的permissions配置项中添加"tabs"权限,否则无法正常获取标签页的URL属性。

内容的提问来源于stack exchange,提问作者Grand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 01:15:04