根据 Chrome native 消息文档,成功调用 connectNative() 会返回一个端口,您可以使用该端口将消息发布到 native 应用程序(Mac 应用程序)。在我的例子中,nativeConnect() 确实返回了一个有效的端口,但是几乎立即触发了对 onDisconnected() 监听器的调用。每当触发监听器时,它都会将“lastError”属性打印到浏览器的控制台,这会给出:
Specified native messaging host not found.
为什么要这样做?生成消息的监听器如下所示:
function onDisconnected() {
console.log("Inside onDisconnected(): " + chrome.runtime.lastError.message);
port = null;
}
在文档底部有一整节关于这个特定错误的内容 ( Native Messaging ),建议的补救措施是 list 文件的命名、放置或定义 (JSON) 不正确,或者主机应用程序是没有命名或位于 list 上说它应该在的地方。文档说 connectNative() 将“在单独的进程中启动主机”,但 Activity Monitor 没有提供 native 主机应用程序已启动的证据。
我调用 connectNative() 如下:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
//var imgdata = JSON.stringify(request.imgdata);
//process it somehow here
port = chrome.runtime.connectNative("com.allinlearning.nmhforbrowserextension");
if (port)
{
console.log("connectNative() returned a non-null port");
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
}
});
根据文档,我的 native 主机 list 文件位于正确的文件夹中,可以很好地解析为 JSON,并且看起来像:
{
"name": "com.allinlearning.nmhforbrowserextension",
"description": "Manifest for native messaging host for Google browser extension",
"path": "/Users/mycomputer1/Documents/nmhost.app",
"type": "stdio",
"allowed_origins": ["chrome-extension://gldheanjpgopipommeingjlnoiamdfol/"]
}
Chrome 扩展也需要一个 list ,在我获得正确的权限部分之前,我无法从 connectNative() 返回一个非空端口,所以我很确定现在这是正确的:
"permissions": [
"nativeMessaging",
"tabs",
"activeTab",
"background",
"http://*/", "https://*/"
]
更新:
想出了如何从 Mac 的终端启动 Chrome 浏览器,并带有允许查看更“详细”日志记录的标志。然后当我运行时我注意到这个输出:
[21285:38915:1231/164417:ERROR:native_process_launcher.cc(131)] Can't find manifest for native messaging host com.allinlearning.nmhforbrowserextension
很明显它找不到主机 list ,但为什么??
最佳答案
对于谷歌浏览器, list 文件的系统级目录是:
~/Library/Application Support/Google/Chrome/NativeMessagingHosts/
用户特定的安装路径位于:
~/Library/Application Support/Chromium/NativeMessagingHosts/
(Mac 的当前 documented 路径不正确 ( patch )。install.sh 中的路径(来自文档中的 the example)是正确的)。
关于javascript - Chrome native 消息传递 -- 为什么我会收到 "Specified native messaging host not found"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27726799/