runtime 平台 API
本教程共 56 篇 · 第 42 篇 · 更新于 2026-08-13 · 约 6 分钟阅读
本节目标:学完你能用 chrome.runtime 拿到扩展自身的信息(资源地址、清单、ID),设置卸载跳转页、打开选项页,并在回调里正确读取 lastError。
chrome.runtime 是扩展的“平台级”命名空间,不依附于任何界面组件。它站在整个扩展的角度提供能力:获取扩展自身的资源路径、读取清单、识别扩展 ID、响应安装与卸载事件等。前面章节里你已经用过 runtime.onInstalled 和 runtime.sendMessage,这一节把其余常用成员集中讲一遍。
42-1 getURL:取扩展内资源的地址
扩展打包后,里面的图片、HTML、JSON 都通过 chrome-extension://<id>/... 这种特殊地址访问。runtime.getURL() 帮你把相对路径拼成完整地址:
const iconUrl = chrome.runtime.getURL('images/icon-48.png');
const pageUrl = chrome.runtime.getURL('popup.html');
console.log(iconUrl); // chrome-extension://abc.../images/icon-48.png
最常见的用途有两个:把扩展图标传给 chrome.notifications 或 chrome.action.setIcon;把内容脚本需要加载的本地资源地址注入到页面。
Warning默认情况下,扩展内部资源只有扩展自身的页面能访问。如果一个普通网页(内容脚本注入到的页面、或别的网站)要加载这个地址,你必须在清单的
web_accessible_resources里显式放行,否则会 404。这是安全设计,别为了方便就写"web_accessible_resources": ["<all_urls>"]。
42-2 getManifest 与 id:读取清单与扩展标识
getManifest() 返回解析后的 manifest.json 对象,不用你自己去 fetch 再 parse:
const manifest = chrome.runtime.getManifest();
console.log('扩展名:', manifest.name);
console.log('版本:', manifest.version);
console.log('是否带 options_ui:', !!manifest.options_ui);
适合根据清单字段动态决定行为,比如“清单里声明了 options_ui 才显示设置入口”。
每个扩展安装后都有一个唯一 ID(形如 32 位十六进制字符串)。它没有方法形式,直接读 runtime.id 属性:
console.log('本扩展 ID:', chrome.runtime.id);
这个 ID 在拼扩展内部资源链接、或和后端校验”请求来自我的扩展”时有用。注意它和清单无关,是浏览器安装时生成的。
42-3 setUninstallURL 与 openOptionsPage:卸载跳转与打开选项页
用户卸载扩展的瞬间,浏览器可以自动打开一个你预设的网址—通常是反馈问卷或挽留页:
chrome.runtime.setUninstallURL('https://example.com/uninstall-survey?ext=myext', () => {
if (chrome.runtime.lastError) {
console.warn('设置卸载页失败:', chrome.runtime.lastError);
}
});
几点提醒:
- 必须在扩展运行期间(比如
onInstalled里)调用。 - 网址必须是 http:// 或 https://(最长 1023 字符);扩展自身页面(chrome-extension:// 协议)不符合 scheme 要求,不能用作卸载页。
- 别收集能定位到个人的敏感信息,问卷页要合规。
如果你的扩展在清单里配了 options_ui(见第 27 节),可以用 runtime.openOptionsPage() 在任意位置唤起选项页:
document.getElementById('open-settings').addEventListener('click', () => {
chrome.runtime.openOptionsPage();
});
弹出页里放一个“设置”按钮、点击就跳到选项页,这是很常见的组合。若清单没声明 options_ui,调用会失败,记得用 lastError 兜底。
42-4 lastError 与其他平台 API
很多 runtime 方法走回调(老式写法)或返回 Promise。回调写法里,出错信息不会抛异常,而是挂在 chrome.runtime.lastError 上:
chrome.runtime.openOptionsPage(() => {
if (chrome.runtime.lastError) {
console.error('打开选项页出错:', chrome.runtime.lastError.message);
return;
}
console.log('选项页已打开');
});
Note
lastError只在回调执行的当下有效,别把它存到外层变量里延后读。Promise 写法(加await)下,错误会以 reject 形式抛出,用 try/catch 接即可。
runtime.getPlatformInfo():返回操作系统和架构(win/mac/linux、x86/arm 等),做平台相关逻辑时有用。runtime.getBrowserInfo():返回浏览器名称和版本。注意这是 Firefox 专属方法,Chrome 没有,直接调用会报错。Chrome 上要拿系统信息,用上面的getPlatformInfo();浏览器版本可以自己从 userAgent 判断。runtime.onStartup:浏览器进程启动时触发;runtime.onInstalled你在第 13 节已见过,首次安装和版本升级都会触发。runtime.reload():重新加载扩展,调试时常点“刷新”按钮等价于它。
42-5 综合场景:初始化与资源放行
把上面几个 API 串起来,最常见的落地点是 runtime.onInstalled。扩展首次安装(或更新)时,可以用它一次性配置好卸载页、写入默认设置。
chrome.runtime.onInstalled.addListener(async (details) => {
// 只在首次安装时跑
if (details.reason !== 'install') return;
// 1. 设置卸载跳转页
chrome.runtime.setUninstallURL('https://example.com/uninstall?ext=myext');
// 2. 写入默认设置
await chrome.storage.local.set({ enabled: true, theme: 'light' });
// 3. 打开选项页引导用户
chrome.runtime.openOptionsPage();
});
details.reason 常见取值有四种:install(首次安装)、update(更新)、chrome_update(浏览器更新导致重载)、shared_module_update(共享模块更新)。把只在安装时做的事用 install 判断包起来,避免每次更新都重复触发。
前面提到 getURL 拿到的内部地址,普通网页默认访问不了。要让某个资源可被网页加载,清单里这样放行:
{
"web_accessible_resources": [
{
"resources": ["images/injected.png", "inject.js"],
"matches": ["<all_urls>"]
}
]
}
resources 是相对路径列表,matches 限定哪些网站能访问。能收窄就收窄,别一上来就 <all_urls>。内容脚本经常需要把一张扩展内的图片插进页面 DOM,这时就靠这个配置配合 getURL 使用。
42-6 Promise 错误处理与方法速查表
新版 Chrome 的 runtime 方法大多返回 Promise,用 await 更清爽,错误用 try/catch 接:
async function openSettings() {
try {
await chrome.runtime.openOptionsPage();
console.log('选项页已打开');
} catch (err) {
console.error('打开失败:', err.message);
}
}
Note回调写法用
lastError,Promise 写法用try/catch,两套不要混。老式 API 不返回 Promise 时只能用lastError,新代码一律推荐await。
把本章出现的成员汇总一下,方便你随用随查:
| 成员 | 作用 | 注意点 |
|---|---|---|
runtime.getURL(path) | 取扩展内资源的完整地址 | 普通网页访问需 web_accessible_resources 放行 |
runtime.getManifest() | 返回解析后的 manifest 对象 | 实时读取,不缓存 |
runtime.id | 扩展唯一 ID | 安装时生成,与清单无关 |
runtime.setUninstallURL(url) | 卸载时跳转页 | http/https 均可,最长 1023 字符 |
runtime.openOptionsPage() | 唤起选项页 | 清单需配 options_ui |
runtime.lastError | 回调里的错误信息 | 仅在回调当下有效 |
runtime.getPlatformInfo() | 系统/架构信息 | 做平台相关逻辑用 |
runtime.reload() | 重新加载扩展 | 调试时等价于点刷新 |
这张表里,getURL、getManifest、setUninstallURL、openOptionsPage 是高频四位,lastError 是配套查错手段,其余按需取用即可。记不住细节就回来翻这一节。
需要强调一点:runtime 系列方法拿的是“扩展自身”的信息。chrome.tabs、chrome.storage 这类 API 操作的是数据或页面,别混为一谈。当你纠结”这个能力该用哪个命名空间”时,先问一句—是在管理扩展自己,还是在操作网页内容?前者多半落在 chrome.runtime 上。
42-7 小结
runtime 这套平台 API 偏“元操作”。用 getURL 取内部资源地址(注意 web_accessible_resources 放行),用 getManifest 读清单、id 取标识,用 setUninstallURL 接住卸载瞬间,openOptionsPage 唤起设置页,回调里用 lastError 查错。它们不像 tabs、storage 那样天天用,但在”扩展管理自己”的场景里是刚需。
下一节进入 i18n 国际化,看看怎么让你的扩展文案支持多语言,而不用为每种语言复制一套代码。