webRequest.getSecurityInfo()无法生效,示例代码无输出求助
问题排查与解决方案
你的核心问题出在代码运行上下文错误和manifest权限配置缺失,以下是具体修复步骤:
1. 修正代码运行位置
webRequest API属于浏览器扩展的**后台脚本(Background Script)**权限,不能在内容脚本(Content Script)中执行。你当前的代码里操作了document.body,说明这是内容脚本,而webRequest.onHeadersReceived监听只能放在后台脚本里。
2. 补全manifest.json必要配置
必须在manifest中声明对应的权限和后台脚本入口,示例配置如下:
{ "manifest_version": 2, "name": "Security Info Logger", "version": "1.0", "permissions": [ "webRequest", "webRequestBlocking", "https://*.mozilla.org/*" ], "background": { "scripts": ["background.js"] } }
注意:如果使用Manifest V3,配置格式略有不同,需要用
service_worker替代scripts,同时权限声明规则一致。
3. 调整代码到后台脚本
将你的logSubject相关代码移到单独的background.js文件中,移除内容脚本相关的DOM操作:
"use strict"; async function logSubject(details) { console.log("it's me"); try { let securityInfo = await browser.webRequest.getSecurityInfo(details.requestId, {}); console.log(details.url); if (securityInfo.state === "secure" || securityInfo.state === "weak") { console.log(securityInfo.certificates[0].subject); } } catch(error) { console.error(error); } } browser.webRequest.onHeadersReceived.addListener(logSubject, {urls: ["https://*.mozilla.org/*"]}, ["blocking"] );
4. 正确调试方式
后台脚本的控制台不会显示在网页的开发者工具里,需要:
- 在Firefox中:打开
about:debugging→ 找到你的扩展 → 点击"检查",打开后台脚本的控制台 - 访问
https://*.mozilla.org下的页面,就能看到"it's me"等调试输出
关于MDN示例无反应的说明
root-cert-stats示例需要触发HTTPS请求才会输出日志,且同样需要通过扩展的后台控制台查看输出,而非网页控制台。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

