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

在React版Chrome扩展中使用chrome.storage报Invalid context type错误

Chrome扩展(React+Webpack)中chrome.storage.local调用报错解决

问题描述

在Webpack编译的React版Chrome扩展中,执行以下代码获取本地存储数据:

chrome.storage.local.get("tasks").then((res) => {
    console.log(res);
});

出现报错:

Uncaught (in promise) Error: Invalid context type provided.
Promise.then (async)
(anonymous) @ App.js:2

但chrome.storage.local本身可正常访问,执行console.log(chrome.storage.local)能输出完整方法集合:{get: ƒ, set: ƒ, remove: ƒ, clear: ƒ, getBytesInUse: ƒ, …}

解决办法

1. 确认运行上下文

Chrome扩展的chrome.storageAPI仅能在扩展自身上下文(如弹出页、背景页、选项页)中正常调用。如果React组件是注入到普通网页的内容脚本,会因上下文隔离导致报错。

  • 确保组件所在页面是扩展的一部分(比如popup.html、options.html),而非注入外部网页的内容脚本。

2. 禁用Webpack的Promise Polyfill

Webpack默认的Promise polyfill可能与Chrome扩展环境的Promise冲突,导致API返回的Promise上下文异常。修改Webpack配置禁用polyfill:

module.exports = {
  // 其他配置项
  resolve: {
    fallback: {
      promise: false
    }
  },
  // 或在Babel配置中关闭polyfill
  babel: {
    presets: [
      ['@babel/preset-env', { useBuiltIns: false }]
    ]
  }
};

3. 改用回调式调用

如果Promise方式仍有问题,切换到Chrome API传统的回调写法:

chrome.storage.local.get("tasks", (res) => {
  if (chrome.runtime.lastError) {
    console.error(chrome.runtime.lastError);
    return;
  }
  console.log(res);
});

4. 检查权限配置

确认manifest.json中已声明storage权限:

{
  "manifest_version": 3,
  "permissions": ["storage"],
  // 其他扩展配置
}

(Manifest V2版本同样需要在permissions数组中添加storage)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:56:06