从chrome扩展到用C#编写的本机主机的本机消息传递

我正在尝试通过本机消息传递从Chrome扩展程序接收消息。 popup.html控制台指示正在发送消息,但我的主机由于某种原因没有收到消息。 我可以看到主机native.exe正在任务管理器中启动,但主机没有收到发送的数据。

popup.js

 document.addEventListener('DOMContentLoaded', function() { var downloadButton= document.getElementById('Button'); downloadButton.addEventListener('click', function () { chrome.tabs.query({currentWindow: true, active: true}, function (tabs) { chrome.tabs.executeScript(tabs[0].id, {file: "myScript.js"}, function (data) { sendNativeMessage(data[0]); }); }); }); }); function sendNativeMessage(msg) { var hostName = "com.google.example"; console.log("Connecting to host: " + hostName); port = chrome.runtime.connectNative(hostName); message = {"text": msg}; port.postMessage(message); console.log("Sent message: " + JSON.stringify(message)); } 

现在,当我从Chrome扩展程序发送消息时,我可以看到popup.html的控制台日志,消息是正确的。

我试图通过使用一些声称有效的代码来测试所有内容,来自Native Messaging Chrome 。 具体来说,我有

native.exe

  static void Main(string[] args) { while (OpenStandardStreamIn() != null || OpenStandardStreamIn() != "") { Console.WriteLine(OpenStandardStreamIn()); } } private static string OpenStandardStreamIn() { //Read first four bytes for length information System.IO.Stream stdin = Console.OpenStandardInput(); int length = 0; byte[] bytes = new byte[4]; stdin.Read(bytes, 0, 4); length = System.BitConverter.ToInt32(bytes, 0); string input = ""; for (int i = 0; i < length; i++) input += (char)stdin.ReadByte(); return input; } 

我仍然试图绕过nativeMessaging,但由于我可以看到通过控制台日志发送的消息,我必须假设错误是我的.exe 。 我创建了注册表项HKCU,并创建了主机的manifest.json文件。 由于扩展是启动.exe ,我很确定所有这些都能正常工作。

如果有人能提供一些帮助,那将非常感激。 谢谢!


编辑:在完全没有改变之后,我无法从我的扩展程序中启动我的native.exe 。 为了解决这个问题,我尝试重写我的发件人以不打开端口:

 ... chrome.tabs.executeScript(tabs[0].id, {file: "myScript.js"}, function (data) { chrome.runtime.sendNativeMessage('com.google.example', {"text":data[0]}, function(response) { if (chrome.runtime.lastError) console.log("ERROR"); } else { console.log("Response: " + response); } }); }); ... 

这根本不起作用。 我不知道我做错了什么,或者当我从我的扩展程序发送消息时,我的主机.exe停止启动的原因。


编辑#2

好消息!

我删除了我的注册表项,然后再次添加它,这次进入Local Machine注册表(即HKLM)。 我再次使用Native Messaging Chrome中的代码从我的主机发送和接收。 现在,当我查看扩展程序的日志时,我可以看到主机的正确响应。 我只是通过调用chrome.runtime.sendNativeMessage(...)来使用“无端口”方法,这对我来说很好。 不幸的是,我没有收到来自主机扩展的消息。 此外,即使收到邮件后,我的host.exe也永远不会退出。 我不确定为什么,但是如果有人可以提供帮助,我将不胜感激。

在我的主机中,我正在尝试将传入的消息写入文件,以测试我收到的消息:

 System.IO.File.WriteAllText(@"path_to_file.txt", OpenStandardStreamIn()); 

注意:我从扩展名传递到主机的消息大约是250KB(因消息而异)。

问题是:

  1. 没有任何内容写入文件。 它完全是空白的。
  2. 该文件需要很长时间才能创建(~4秒)。
  3. 我的host.exe实例永远不会终止。 它仍在运行(我可以在任务管理器中查看)。

为了让我的扩展工作,我按照以下步骤操作:

  1. 我删除了我的注册表项,然后在我的HKLM注册表中重新添加它。
  2. 虽然不必要,但host.exe实际上只需要从扩展中接收一条消息,因此我将之前的“开放端口”消息更改为“无端口”消息,即

    chrome.runtime.sendNativeMessage(...);

  3. 重要的是,当我更改我从{"text":data[0]}发送到简单字符串{"text":"Hello from Chrome!"} ,一切都开始顺利进行。 data[0]是一个大约250KB的字符串,根据开发人员的站点 ,它绝对应该是可接受的消息大小。 但是,我为这个问题创建了一个不同的问题,因为我能够解决我遇到的一般消息发送和接收问题。