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

Chrome扩展Manifest V3开发报错:Service Worker注册失败及navigator.getBattery未定义

解决Chrome扩展Manifest V3中的两个错误

错误原因分析

1. Service worker registration failed. Status code: 15

这个错误是因为你在popup.html中直接引入了作为Service Worker的background.js,导致脚本在错误的上下文环境中运行,同时Service Worker本身不支持navigator.getBattery这类API,触发了注册失败。另外manifest.json中多余的"background"权限也属于无效配置。

2. Uncaught TypeError: navigator.getBattery is not a function

navigator.getBattery是仅存在于DOM上下文(比如popup弹窗、网页、内容脚本)的API,Service Worker的后台上下文没有这个接口,所以在background.js中调用会报错。

修复方案

1. 修正manifest.json

移除无效的"background"权限:

{
  "manifest_version": 3,
  "name": "Badge Extension",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "notifications",
    "scripting"
  ]
}

2. 调整popup.html的脚本引入

把原来引入的background.js换成独立的popup.js:

<!DOCTYPE html>
<html>
  <head>
    <title>Badge Extension</title>
    <script src="popup.js"></script>
  </head>
  <body></body>
</html>

3. 迁移电池状态逻辑到popup.js

创建popup.js文件,将原background.js中的电池相关代码移到这里,并补充updateBatteryStatus函数实现:

navigator.getBattery().then((battery) => {
  updateBatteryStatus(battery);
  battery.onlevelchange = () => updateBatteryStatus(battery);
  battery.onchargingchange = () => updateBatteryStatus(battery);
});

function updateBatteryStatus(battery) {
  // 更新扩展图标badge的逻辑示例
  const batteryLevel = Math.floor(battery.level * 100);
  chrome.action.setBadgeText({ text: batteryLevel.toString() });
  // 充电时显示绿色,未充电显示橙色
  chrome.action.setBadgeBackgroundColor({ color: battery.charging ? '#4CAF50' : '#FF9800' });
}

4. 清理background.js

如果background.js没有其他后台逻辑,可以留空;如果需要后台功能,只保留Service Worker支持的API逻辑(比如监听扩展安装、消息事件等),不要放入DOM相关API调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:52:36