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

如何阻止开发者直接调用chrome.runtime.sendMessage?

解决直接调用chrome.runtime.sendMessage的警告方案

一、IDE实时提示警告(用ESLint规则)

用ESLint的no-restricted-properties规则,直接限制调用chrome.runtime.sendMessage,开发者在IDE里输入代码时会立刻收到提示。

在项目的.eslintrc.js中添加以下规则:

module.exports = {
  rules: {
    "no-restricted-properties": [
      "warn",
      {
        object: "chrome.runtime",
        property: "sendMessage",
        message: "请用项目封装的消息发送方法,别直接调用 chrome.runtime.sendMessage"
      }
    ]
  }
};

二、TypeScript类型覆盖(IDE+编译双重警告)

通过扩展Chrome的类型声明,把sendMessage标记为过时或者不可调用,既能在IDE里提示,也能在编译阶段触发警告。

  1. 在项目根目录创建types/chrome-override.d.ts文件:
declare namespace chrome.runtime {
  // 标记为过时,IDE会弹出警告提示
  @deprecated("请用项目封装的消息发送方法,别直接调用 chrome.runtime.sendMessage")
  function sendMessage(...args: any[]): void;

  // 要是想更严格,直接设为never类型,编译时会报错阻止构建
  // function sendMessage(...args: any[]): never;
}
  1. 在tsconfig.json里确保这个类型文件被包含:
{
  "include": ["src/**/*", "types/**/*"]
}

三、编译阶段强制检查

把ESLint检查加到构建流程里,确保不合规代码无法通过编译。在package.json的scripts中添加:

{
  "scripts": {
    "lint": "eslint src/**/*.ts",
    "prebuild": "npm run lint"
  }
}

这样每次执行构建前都会先跑ESLint检查,要是发现直接调用chrome.runtime.sendMessage的代码,会抛出警告(把规则里的"warn"改成"error"就能直接报错阻止构建)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:18:15