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

Chrome扩展中如何在后台脚本与弹窗脚本间共享常量?

Chrome扩展静态常量跨脚本共享方案

1. 单独创建共享常量文件(最推荐)

创建独立的constants.js文件统一存放所有共享常量,再在需要的脚本中引入,从根源避免重复声明。

针对Manifest V3(支持ES模块)

先在manifest.json中给相关脚本设置type: "module":

{
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html里的脚本标签也要添加type="module":

<script src="popup.js" type="module"></script>

constants.js中定义常量:

export const API_BASE_URL = "https://api.example.com";
export const MAX_RETRY_COUNT = 3;

在background.js和popup.js中直接导入使用:

import { API_BASE_URL, MAX_RETRY_COUNT } from "./constants.js";
console.log(API_BASE_URL);

针对Manifest V2(或不支持模块的场景)

用IIFE把常量挂载到全局对象,适配无window的后台脚本:
constants.js:

(function() {
  self.EXTENSION_CONSTANTS = {
    API_BASE_URL: "https://api.example.com",
    MAX_RETRY_COUNT: 3
  };
})();

background.js中通过importScripts引入:

importScripts(chrome.runtime.getURL("constants.js"));
console.log(EXTENSION_CONSTANTS.API_BASE_URL);

popup.html中先引入常量文件再加载业务脚本:

<script src="constants.js"></script>
<script src="popup.js"></script>

popup.js直接使用全局常量:

console.log(EXTENSION_CONSTANTS.MAX_RETRY_COUNT);

2. 利用Chrome存储API存储静态常量

适合需要持久化(扩展重启后仍保留)的静态常量,初始化时写入存储,后续脚本统一读取。

background.js初始化写入:

// 仅在安装/更新时写入,避免重复操作
chrome.runtime.onInstalled.addListener(() => {
  const constants = {
    API_BASE_URL: "https://api.example.com",
    MAX_RETRY_COUNT: 3
  };
  chrome.storage.local.set({ extensionConstants: constants });
});

任意脚本中读取(注意异步特性):

chrome.storage.local.get("extensionConstants", (result) => {
  const { API_BASE_URL, MAX_RETRY_COUNT } = result.extensionConstants;
  console.log(API_BASE_URL);
});

3. 在Manifest文件中嵌入常量

将常量写入manifest.json的自定义字段,通过Chrome API读取,无需额外文件。

manifest.json添加自定义字段:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "extensionConstants": {
    "API_BASE_URL": "https://api.example.com",
    "MAX_RETRY_COUNT": 3
  }
}

任意脚本中读取:

const manifest = chrome.runtime.getManifest();
const { API_BASE_URL, MAX_RETRY_COUNT } = manifest.extensionConstants;
console.log(API_BASE_URL);

注意:此方法不适合存储敏感信息,且常量无法动态修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:55:19