Chrome扩展调用webRequest.onHeadersReceived无日志与弹窗问题求助
问题排查与修复方案
1. 核心错误:manifest.json 配置结构错误
你当前把background字段放在了browser_action的子级里,这是完全错误的,background是manifest的顶级配置项,放在子级里浏览器根本不会加载你的background.js,自然回调不会触发。同时要补充webRequestBlocking权限、设置后台页持续运行,才能正常监听网络请求。
修正后的manifest.json参考:
{ "description": "truc écolo", "manifest_version": 2, "name": "PolNum", "version": "0.1", "icons": { "48": "icons/icon48.png" }, "permissions": [ "activeTab", "http://*/*", "https://*/*", "tabs", "notifications", "webRequest", "webRequestBlocking", "storage" ], "background": { "scripts": ["background.js"], "persistent": true }, "browser_action": { "default_popup" :"popup.html", "default_icon": { "16": "icons/icon16.png", "32": "icons/icon32.png" } } }
2. background.js 代码修正
你要统计文件大小需要读取的是响应头不是请求头,所以opt_extraInfoSpec要传入responseHeaders才能拿到返回的资源大小参数:
var callback = function(details) { console.log('Les Headers ont ete recus', details); // 提取Content-Length字段获取资源大小,单位为字节 const contentLength = details.responseHeaders?.find(header => header.name.toLowerCase() === 'content-length')?.value; if (contentLength) { console.log('当前资源大小:', contentLength, '字节'); } alert("BBBBBBBBBBBBBBBBBBBBB"); } var filter = { urls: ['<all_urls>'] }; var opt_extraInfoSpec = ["responseHeaders", "blocking"]; chrome.webRequest.onHeadersReceived.addListener( callback, filter, opt_extraInfoSpec );
3. 调试注意事项
- 后台脚本的日志不会出现在普通网页的控制台中,你需要打开
chrome://extensions/,开启右上角「开发者模式」,找到你的扩展,点击「背景页」打开专属控制台,才能看到console.log输出。 - 每次修改代码后,一定要在扩展管理页点击对应扩展的「刷新」按钮,修改才会生效。
内容的提问来源于stack exchange,提问作者Ostrale
相关产品推荐
相关产品推荐

