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

Chrome扩展调用chrome.system.memory.getInfo报错:memory未定义

解决Chrome扩展调用chrome.system.memory.getInfo报错的方案

报错原因

你在content script中直接调用chrome.system.memory.getInfo,但在Manifest V3中,content script运行在宿主网页的上下文,无法直接访问chrome.system这类系统级特权API,导致chrome.system未定义,触发Cannot read properties of undefined (reading 'memory')错误。

解决步骤

1. 修改Manifest配置,添加后台服务Worker

更新manifest.json,新增background字段指定后台脚本:

{
  "manifest_version": 3,
  "name": "Memory Monitor",
  "version": "1.0",
  "content_scripts": [
        {
          "js": [
            "scripts/content.js"
          ],
          "matches": ["<all_urls>"]
        }
      ],
  "permissions": [
      "system.memory"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

2. 创建后台脚本background.js,处理API调用

在后台脚本中调用chrome.system.memory.getInfo,并通过消息监听接收content script的请求:

// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'getMemoryInfo') {
    chrome.system.memory.getInfo(info => {
      sendResponse(info);
    });
    // 异步调用需返回true,保持消息通道开放
    return true;
  }
});

3. 修改content script,通过消息传递获取结果

更新content.js,不再直接调用API,而是向后台发送消息请求内存信息:

// content.js
chrome.runtime.sendMessage({ type: 'getMemoryInfo' }, info => {
  console.log('内存信息:', info);
});

原理说明

Manifest V3对扩展的权限做了严格隔离:

  • content script仅能访问有限的Chrome API(如chrome.runtime、chrome.storage),无法直接调用系统级API
  • 后台服务Worker(service worker)拥有扩展的完整权限,可以访问chrome.system这类特权API
  • 通过chrome.runtime.sendMessage和chrome.runtime.onMessage实现content script与后台的通信,间接获取系统信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:21:36