Chrome扩展适配Firefox时runtime.sendMessage报uncaught exception: Object错误
问题原因
- 异步处理逻辑差异:Chrome 调用
runtime.sendMessage时如果未传入回调函数、且接收方无响应,不会抛出未捕获异常;但 Firefox 中该方法默认返回 Promise,若接收方没有返回响应或调用sendResponse,Promise 会被置为 rejected 状态,未添加 catch 处理时就会抛出uncaught exception: Object错误。 - 参数校验严格度差异:Chrome 对
sendMessage的可选参数校验规则更宽松,Firefox 对参数格式、必填项的校验更严格。 - 命名空间兼容问题:Chrome 扩展默认使用
chrome命名空间,Firefox 虽做了兼容适配,但部分场景下使用标准browser命名空间稳定性更高。
解决方法
方案1:补全回调或异常捕获
最简单的修复方式是添加空回调函数,或者对返回的 Promise 添加 catch 处理:// 方式1:添加空回调 chrome.runtime.sendMessage({ type: "update-title", options: { title, url }, }, () => {}); // 方式2:捕获Promise异常 chrome.runtime.sendMessage({ type: "update-title", options: { title, url }, }).catch(err => { // 无响应的普通报错可直接忽略,也可按需打印日志 console.debug("消息发送无响应", err); });方案2:完善 background 消息监听逻辑
在background.js的onMessage监听逻辑中,显式调用sendResponse返回响应,哪怕是空结果:chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === "update-title") { // 原有业务逻辑 sendResponse({ status: "success" }); // 如果是异步处理逻辑,需要额外返回true告知浏览器等待响应 // return true; } });方案3:统一多浏览器命名空间适配
针对多浏览器适配场景,可提前声明通用API对象,避免命名空间兼容问题:// 全局提前声明兼容API对象 const extensionAPI = window.browser || window.chrome; // 后续所有扩展API调用都使用extensionAPI extensionAPI.runtime.sendMessage({ type: "update-title", options: { title, url }, }, () => {});
内容的提问来源于stack exchange,提问作者ted
相关产品推荐
相关产品推荐

