【发布时间】:2015-02-27 21:04:43
【问题描述】:
根据 Chrome Native Messaging 文档,对 connectNative() 的成功调用会返回一个端口,您可以使用该端口将消息发布到本机应用程序(Mac 应用程序)。在我的例子中,nativeConnect() 确实返回了一个有效的端口,但是对 onDisconnected() 监听器的调用几乎立即被触发。每当触发侦听器时,它都会将“lastError”属性打印到浏览器的控制台,这给出:
Specified native messaging host not found.
为什么要这样做?产生 msg 的监听器如下所示:
function onDisconnected() {
console.log("Inside onDisconnected(): " + chrome.runtime.lastError.message);
port = null;
}
在文档底部有一个关于这个特定错误的完整部分 (Native Messaging),建议的补救措施是清单文件的命名、放置或定义 (JSON) 不正确,或者主机应用程序是未命名或位于清单中应有的位置。文档说 connectNative() 将“在单独的进程中启动主机”,但 Activity Monitor 没有提供任何证据表明本机主机应用程序已启动。
我如下调用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);
}
});
根据文档,我的本机主机清单文件位于正确的文件夹中,解析为 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 扩展程序也需要一个清单,在我获得权限部分之前,我无法从 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
很清楚它找不到主机清单,但为什么??
【问题讨论】:
-
好吧,显然重要的是你把清单放在哪里。您所说的只是“根据文档在正确的文件夹中”。请包含文件的完整路径。
-
@Xan,谢谢。两件事:1)我终于找到了清单,但只能通过添加尝试系统范围解决方案所需的缺失目录:/Library/Google/Chrome/NativeMessagingHosts。 2) 我仍然无法让它在这里工作(用户特定的位置):~/Library/Application Support/Google/Chrome/Default/NativeMessagingHosts。因为当我们部署时,我们可能只被允许安装在用户特定的位置,我确实需要找到一个解决方案,所以我把这个问题留了下来。此外,它可能会使其他人受益。
-
@Alyoshak 您可能使用的是 Chrome Canary,这意味着您必须
Google/Chrome\ Canary...
标签: javascript google-chrome google-chrome-extension chrome-native-messaging