Chrome扩展问题:点击弹窗获取当前页面源码遇未检查运行时错误
解决Chrome扩展弹窗与Content Script通信失败问题
核心问题分析
出现Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist错误,本质是当前活跃标签页中没有加载对应的Content Script,导致弹窗发送的消息没有接收端。常见触发场景包括:扩展重新加载后旧标签页未自动注入Content Script、目标页面不在Content Script的匹配范围内、Manifest配置存在语法问题。
具体解决方案
1. 修复Manifest配置
清理冗余权限,确保JSON语法完全正确(注意引号统一、结构闭合):
{ "manifest_version": 2, "name": "xxxx", "description": "xxxx", "version": "1.01", "author": "xxxx", "permissions": [ "tabs", "<all_urls>", "notifications", "webRequest", "webNavigation", "management", "webRequestBlocking", "alarms" ], "externally_connectable": { "matches": ["http://*/*", "https://*/*"] }, "background": { "scripts": ["background.js"], "persistent": true }, "content_scripts": [ { "matches": ["http://*/*", "https://*/*"], "js": ["content.js"] } ], "browser_action": { "default_icon": "logo.png", "default_popup": "popup.html" } }
2. 强制注入Content Script后再发消息
修改popup.js,在点击按钮时先尝试注入Content Script,确保接收端存在后再发送消息:
document.addEventListener("DOMContentLoaded", function () { var getCodeButton = document.getElementById("getCodeButton"); getCodeButton.addEventListener("click", function () { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { const activeTab = tabs[0]; // 先注入Content Script,确保页面中有接收端 chrome.tabs.executeScript(activeTab.id, { file: "content.js" }, function() { if (chrome.runtime.lastError) { console.error("注入失败:", chrome.runtime.lastError.message); return; } // 注入成功后发送消息 chrome.tabs.sendMessage(activeTab.id, { action: "getSourceCode" }, function (response) { if (chrome.runtime.lastError) { console.error("通信失败:", chrome.runtime.lastError.message); return; } // 将获取到的源码显示到弹窗中 document.getElementById("sourceCode").textContent = response.sourceCode; }); }); }); }); });
3. 测试注意事项
- 扩展重新加载后,若使用旧标签页测试,需手动刷新页面让Content Script注入;使用上述
executeScript方式则无需手动刷新。 - 避免在Chrome内部页面(如
chrome://extensions/、about:blank)测试,这类页面无法注入Content Script。
内容的提问来源于stack exchange,提问作者Laurent
相关产品推荐
相关产品推荐

