Pasé algunas horas hoy investigando cómo hacer que la mensajería nativa de Chrome funcione con un host nativo de C#. Conceptualmente era bastante simple, pero hubo algunos inconvenientes que resolví con la ayuda (en parte) de estas otras preguntas:
Chrome de mensajería nativa
Mensajería nativa desde la extensión de Chrome al host nativo escrito en C#
Muy lento para pasar una "gran" cantidad de datos de Chrome Extension a Host (escrito en C#)
Mi solución se publica a continuación.
Suponiendo que el manifiesto esté configurado correctamente, aquí hay un ejemplo completo para hablar con un host C# usando el método "puerto":
using System; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace NativeMessagingHost { class Program { public static void Main(string[] args) { JObject data; while ((data = Read()) != null) { var processed = ProcessMessage(data); Write(processed); if (processed == "exit") { return; } } } public static string ProcessMessage(JObject data) { var message = data["text"].Value<string>(); switch (message) { case "test": return "testing!"; case "exit": return "exit"; default: return "echo: " + message; } } public static JObject Read() { var stdin = Console.OpenStandardInput(); var length = 0; var lengthBytes = new byte[4]; stdin.Read(lengthBytes, 0, 4); length = BitConverter.ToInt32(lengthBytes, 0); var buffer = new char[length]; using (var reader = new StreamReader(stdin)) { while (reader.Peek() >= 0) { reader.Read(buffer, 0, buffer.Length); } } return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer)); } public static void Write(JToken data) { var json = new JObject(); json["data"] = data; var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None)); var stdout = Console.OpenStandardOutput(); stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF)); stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF)); stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF)); stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF)); stdout.Write(bytes, 0, bytes.Length); stdout.Flush(); } } } Si no necesita comunicarse activamente con el host, usar runtime.sendNativeMessage funcionará bien. Para evitar que el host se cuelgue, simplemente elimine el bucle while y realice la lectura/escritura una vez.
Para probar esto, utilicé el proyecto de ejemplo proporcionado por Google aquí: https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging
Nota: estoy usando Json.NET para simplificar el proceso de serialización/deserialización de json.
¡Espero que esto sea útil para alguien!