You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Chrome扩展Service Worker中使用chrome.storage遇错求助

问题解决:Chrome扩展中chrome.storage.local调用报错的修复

核心错误原因

你的manifest.json中permissions字段被错误嵌套在action内部,导致扩展无法获取storage权限,进而出现chrome.storage为undefined的报错。此外代码中还有几处逻辑问题需要修正。

修复步骤

1. 修正manifest.json的权限配置

将permissions从action字段中移出,作为根级字段存在:

{
  "manifest_version": 3,
  "name": "Tab Counter",
  "author": "CatRass",
  "description": "Count total amount of opened tabs",
  "version": "1.0",
  "action": {
    "default_popup": "main.html",
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs",
    "storage"
  ],
  "background": {
    "service_worker": "js/background.js",
    "type": "module"
  }
}

2. 修正background.js的逻辑错误

  • 初始化时定义初始计数为0
  • 修复chrome.storage.get的取值(应该取result.tabsOpened而非result.key)
  • 实现标签页打开时的计数累加逻辑
chrome.runtime.onInstalled.addListener(async () => {
  chrome.action.setBadgeText({ text: "0" });
  // 初始化存储的计数为0
  await chrome.storage.local.set({ "tabsOpened": 0 });
});

chrome.tabs.onCreated.addListener(async () => {
  console.log("Tab Opened");
  // 获取当前计数并累加
  const result = await chrome.storage.local.get(["tabsOpened"]);
  const currentCount = result.tabsOpened || 0;
  const newCount = currentCount + 1;
  await chrome.storage.local.set({ "tabsOpened": newCount });
  // 更新徽章显示
  chrome.action.setBadgeText({ text: newCount.toString() });
  console.log("Current tab count:", newCount);
});

额外说明

  • 使用async/await替代Promise链式调用,代码更易读
  • 初始化时直接设置徽章为0,更符合统计逻辑
  • 处理result.tabsOpened可能为undefined的情况,默认取0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:52:35