Chrome扩展:popup.js向content-script.js发消息报错咨询
问题修复方案
错误根源分析
「could not establish connection. Receiving end does not exist.」
核心问题是content.js的消息监听器被嵌套在页面新增按钮的点击事件中——只有用户手动点击页面上的"test"按钮后,监听器才会注册。但popup.js点击"Record"按钮时,会先注入content.js并立刻发送消息,此时监听器尚未注册,导致接收端不存在。「Error handling response: TypeError...Unexpected property: 'hello'」
该错误是因错误调用chrome.runtime.sendMessage导致的:误将消息对象放到了options参数位置。当前代码中使用chrome.tabs.sendMessage的参数顺序正确,此错误应为历史调用问题。
具体修复步骤及代码修改
1. 调整content.js的监听器位置
将消息监听器移到按钮点击事件外部,确保content.js注入页面后立刻注册监听器:
const overlayButton = document.createElement("button"); overlayButton.innerText = "test"; document.body.appendChild(overlayButton); // 注入后立即注册消息监听器,无需等待按钮点击 chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.hello === "startRecording") { console.log("收到popup消息:", message); } return true; // 若无需异步响应可移除,保留不影响功能 }); // 页面按钮的独立逻辑 overlayButton.addEventListener('click', function() { console.log("页面test按钮被点击"); });
2. 优化popup.js的消息发送逻辑
添加错误处理,确保content.js注入成功后再发送消息:
const textBtn = document.querySelector('.testbtn'); textBtn.addEventListener('click', function() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { const currentTabId = tabs[0].id; console.log("当前标签页ID:", currentTabId); chrome.scripting.executeScript({ files: ["content.js"], target: { tabId: currentTabId } }, (results) => { // 检查注入是否失败 if (chrome.runtime.lastError) { console.error("注入content.js失败:", chrome.runtime.lastError); return; } // 注入成功后发送消息 chrome.tabs.sendMessage(currentTabId, { hello: "startRecording", duration: 60, quality: "720p" }, (response) => { // 处理消息发送错误 if (chrome.runtime.lastError) { console.error("发送消息失败:", chrome.runtime.lastError); return; } console.log("消息发送成功"); }); }); }); });
3. 配置文件说明
manifest.json的权限配置已满足需求,无需额外修改。
内容的提问来源于stack exchange,提问作者Aviato
相关产品推荐
相关产品推荐

