React Chrome扩展:popup.tsx向content script发消息报错
Chrome扩展Manifest V3:Popup向Content Script发消息报错解决
问题描述
开发Manifest V3版本的Chrome扩展时,点击Popup组件中的按钮尝试向Content Script发送消息,触发以下错误:
Error handling response: TypeError: Cannot read properties of undefined (reading 'farewell')
核心原因
报错本质是sendMessage的回调中response为undefined,可能由以下情况导致:
- Content Script未在当前页面成功加载
- 消息监听的条件判断不匹配,未执行
sendResponse - 当前标签页对象无效,消息未成功发送
- 消息通道提前关闭,未收到响应
解决方案
1. 为消息发送添加错误处理
在Popup的消息发送回调中,先检查chrome.runtime.lastError捕获发送失败的原因,同时避免直接读取response.farewell:
const ValidateTwitterTweets = () => { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { if (!tabs.length || !tabs[0].id) { alert("无法获取当前标签页"); return; } chrome.tabs.sendMessage( tabs[0].id as number, { sender: "www", instruction: "api" }, function (response) { // 捕获消息发送失败的错误 if (chrome.runtime.lastError) { alert(`消息发送失败:${chrome.runtime.lastError.message}`); return; } // 安全读取响应字段 alert(response?.farewell || "未收到有效响应"); } ); }); };
2. 确保Content Script正确加载
- 测试时使用普通网页(如百度、Twitter),浏览器内置页面(
chrome://、edge://等)或扩展自身页面不会加载Content Script - 如果需要动态注入Content Script,可改用
chrome.scripting.executeScript主动注入:
const ValidateTwitterTweets = async () => { const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); const tab = tabs[0]; if (!tab.id) { alert("无法获取当前标签页"); return; } try { // 主动注入Content Script await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["contentScript.js"] }); // 注入成功后发送消息 chrome.tabs.sendMessage( tab.id, { sender: "www", instruction: "api" }, function (response) { if (chrome.runtime.lastError) { alert(`错误:${chrome.runtime.lastError.message}`); return; } alert(response?.farewell || "无响应"); } ); } catch (err) { alert(`注入脚本失败:${(err as Error).message}`); } };
3. 完善Content Script的消息监听
添加日志调试,确保消息字段匹配,同时覆盖所有消息场景:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { console.log("收到消息内容:", msg); // 打印消息,确认字段是否正确 if (msg.sender === "www" && msg.instruction === "api") { console.log("Message received from www"); alert("Message received from www"); sendResponse({ farewell: "to-do" }); } else { // 处理未知指令,避免返回undefined sendResponse({ farewell: "未知指令" }); } // 若后续有异步操作,需返回true保持消息通道打开 // return true; });
4. 验证Manifest配置
确认content_scripts配置正确,确保匹配规则覆盖测试页面:
"content_scripts": [ { "matches": ["<all_urls>"], "js": ["contentScript.js"] } ]
内容的提问来源于stack exchange,提问作者winnie
相关产品推荐
相关产品推荐

