网页向Chrome扩展发送消息失败,Background未接收content.js消息求助
问题诊断与修复方案
你的问题核心是内部通信误用了外部消息监听API,导致content.js发送的消息无法被background.js接收到。下面是具体的问题分析和修复步骤:
关键问题点
- 错误的消息监听事件:content.js属于扩展的一部分,属于内部通信场景,但你在background.js里用了
chrome.runtime.onMessageExternal——这个API是专门用来接收**外部网页(非扩展内页面)**发送的消息的,自然收不到content.js的内部消息。 - 多余的配置项:
manifest.json里的externally_connectable同样是给外部网页和扩展通信用的,你的场景是扩展内部的content script与background通信,完全不需要这个配置,可以直接删掉。
修复后的代码示例
1. 修改background.js
把chrome.runtime.onMessageExternal替换为内部通信对应的chrome.runtime.onMessage:
console.log("background page in loading..."); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log("listener received request"); console.log(request); if (request.openUrlInEditor) console.log("Open :" + request.openUrlInEditor); sendResponse({success : "success"}); } );
2. 简化content.js(可选优化)
内部通信时,sendMessage可以不用指定扩展ID(如果是给自己的扩展发消息),当然保留ID也不会影响功能:
// 方式1:省略扩展ID(推荐内部通信使用) chrome.runtime.sendMessage({openUrlInEditor: "https://www.google.com"}, function(response) { if (response && !response.success) handleError(url); }); // 方式2:保留扩展ID也可行,不影响逻辑 // chrome.runtime.sendMessage("acldjllcapdfejdafbkjnfmpahdkendo", {openUrlInEditor: "https://www.google.com"}, function(response) { // if (response && !response.success) handleError(url); // });
3. 清理manifest.json
删掉无用的externally_connectable配置项,其他部分保持不变:
{ "name": "My Checker", "version": "1.0", "description": "http://www.abc.dev Extension!", "manifest_version": 2, "permissions": [ "*://*.google.com/" ], "background": { "scripts": ["background.js"], "persistent": false }, "content_scripts": [ { "matches": ["*://*.abc.dev/*"], "js": ["jquery-3.3.1.min.js", "content.js"], "run_at": "document_end" } ], "browser_action": { "default_popup": "popup.html" } }
验证方法
- 重新加载扩展(在
chrome://extensions/页面点击扩展卡片的刷新按钮) - 打开匹配的
abc.dev页面,打开开发者工具查看content.js的运行日志 - 打开扩展的background页面控制台(在
chrome://extensions/页面点击"背景页"链接),查看是否成功接收到消息
这样修改后,content.js发送的消息就能被background.js正确接收啦!
内容的提问来源于stack exchange,提问作者Phạm Đức Vinh
相关产品推荐
相关产品推荐

