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

Chrome扩展无法将值存入chrome.storage.local?求助排查

问题分析与解决方案

你的代码有三个关键问题导致chrome.storage.local.set的回调无输出:

1. 未声明storage权限

Chrome扩展使用chrome.storage API必须在manifest.json的permissions数组里明确声明"storage"权限,否则API调用会静默失败(无报错但不执行)。

2. 代码执行顺序错误

chrome.webRequest.onBeforeRequest的回调是异步触发的——只有当匹配的网络请求发生时才会执行。你现在把chrome.storage.local.set写在监听函数外面,脚本初始化时就会立刻执行,这时候point还没被赋值(仍是undefined),后续请求触发回调给point赋值后,这段set代码也不会再运行。

正确做法是把chrome.storage.local.set移到监听回调内部,确保每次拿到请求里的point值后再存入storage。

3. urls匹配规则无效

你在监听配置里写了{ urls: [url] },但url是未定义的变量,导致监听规则不生效。需要替换成和host_permissions一致的具体规则,比如"*://*.cnn.com/*"。


修改后的manifest.json

{
  "manifest_version": 3,
  "version": "1.0",
  "name": "Hello World!",
  "description": "Learning how to make a chrome extension!",
  "icons": {
    "16": "images/puppy16.png",
    "48": "images/puppy48.png",
    "128": "images/puppy128.png"
  },
  "action": {
    "default_icon": "images/puppy.png",
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["*://*.cnn.com/"],
  "permissions": ["webRequest", "activeTab", "tabs", "storage"],
  "content_scripts": [
    {
      "matches": ["*://cnn.com/*"],
      "js": ["contentScript.js"]
    }
  ]
}

修改后的background.js

(function () {
    chrome.webRequest.onBeforeRequest.addListener(
        function (details) {
            // 先判断requestBody是否存在,避免报错
            if (!details.requestBody?.raw?.length) return;
            
            const postedString = decodeURIComponent(String.fromCharCode.apply(null,
                new Uint8Array(details.requestBody.raw[0].bytes)));
            console.log(postedString);
            
            try {
                const body = JSON.parse(postedString);
                const point = body.CenterPoint?.Point;
                if (point) {
                    console.log(point);
                    chrome.storage.local.set({ 'key': point }, function () {
                        console.log('Value is set to ' + point);
                    });
                }
            } catch (e) {
                console.log('解析请求体失败:', e);
            }
        },
        { urls: ["*://*.cnn.com/*"] },
        ["requestBody"]
    );
})();

额外补充:

  • 增加requestBody存在性判断和JSON解析的try-catch,避免请求体格式不符合预期时脚本崩溃
  • 把全局变量point改成回调内部的常量,减少全局污染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:50:25