如何避免Chrome扩展调用Native Messaging时的未找到主机报错提示
避免Chrome扩展Native Messaging未找到主机的报错提示
要解决这个问题,核心就是主动捕获并处理chrome.runtime.lastError——Chrome会把未被检查的lastError当成未处理的运行时错误,显示在扩展列表里,只要你主动处理它,就能消除这个提示。
具体做法分两种场景:
1. 用chrome.runtime.connectNative()建立长连接
调用方法后立即检查lastError,如果存在就处理(比如提示用户安装对应Windows应用),示例代码:
const nativeHostPort = chrome.runtime.connectNative('你的本地消息主机ID'); // 主动检查错误 if (chrome.runtime.lastError) { // 这里可以给用户友好提示,比如弹出通知或页面提示 console.log('请先安装对应的Windows应用'); // 也可以用chrome.notifications.create弹出系统通知 } else { // 正常处理连接后的消息逻辑 nativeHostPort.onMessage.addListener((message) => { // 处理来自本地应用的消息 }); nativeHostPort.onDisconnect.addListener(() => { // 连接断开时也可以检查错误 if (chrome.runtime.lastError) { console.log('连接异常断开:', chrome.runtime.lastError.message); } }); }
2. 用chrome.runtime.sendNativeMessage()发送单次消息
在回调函数里检查lastError,示例代码:
chrome.runtime.sendNativeMessage( '你的本地消息主机ID', { content: '要发送的内容' }, (response) => { // 主动检查发送过程中的错误 if (chrome.runtime.lastError) { console.log('发送失败,请先安装对应应用'); } else { // 处理本地应用返回的响应 } } );
只要确保每次调用Native Messaging相关API后,都主动检查并处理chrome.runtime.lastError,Chrome就不会在扩展列表里显示那个未捕获的错误提示了。
内容的提问来源于stack exchange,提问作者SantK
相关产品推荐
相关产品推荐

