如何在 chrome 扩展本机消息传递和 c# 应用程序之间发送/接收消息

Posted

技术标签:

【中文标题】如何在 chrome 扩展本机消息传递和 c# 应用程序之间发送/接收消息【英文标题】:How to send / receive message between chrome extension native messaging and c# app 【发布时间】:2016-05-20 17:06:53 【问题描述】:

我是 chrome 扩展的新手,所以我需要通过使用原生消息与 c#.exe 应用程序通信消息来开发 chrome 扩展

现在的问题:我可以使用 c# 在扩展程序(chrome.runtime.connectNative(hostName))之间连接,但我无法发送/接收消息

这是我的代码

ma​​in.js

// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var port = null;

var getKeys = function(obj)
   var keys = [];
   for(var key in obj)
      keys.push(key);
   
   return keys;



function appendMessage(text) 
  document.getElementById('response').innerhtml += "<p>" + text + "</p>";


function updateUiState() 
  if (port) 
    document.getElementById('connect-button').style.display = 'none';
    document.getElementById('input-text').style.display = 'block';
    document.getElementById('send-message-button').style.display = 'block';
   else 
    document.getElementById('connect-button').style.display = 'block';
    document.getElementById('input-text').style.display = 'none';
    document.getElementById('send-message-button').style.display = 'none';
  


function sendNativeMessage() 
  message = "text": document.getElementById('input-text').value;
  port.postMessage(message);
  appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");


function onNativeMessage(message) 
  appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");


function onDisconnected() 
  appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
  port = null;
  updateUiState();


function connect() 
  var hostName = "com.google.chrome.example.echo";
  appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
  port = chrome.runtime.connectNative(hostName);
  port.onMessage.addListener(onNativeMessage);
  port.onDisconnect.addListener(onDisconnected);
  updateUiState();


document.addEventListener('DOMContentLoaded', function () 
  document.getElementById('connect-button').addEventListener(
      'click', connect);
  document.getElementById('send-message-button').addEventListener(
      'click', sendNativeMessage);
  updateUiState();
);

app.exe - C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace sign

    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["message"].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))["data"];
        

        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();
        
    

.json

// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


  "name": "com.google.chrome.example.echo",
  "description": "Chrome Native Messaging API Example Host",
  "path": "native-messaging-example-host.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
  ]

.bat

@echo off

start %~dp0/Debug/sign.exe

.manifest.json


  // Extension ID: knldjmfmopnpolahpmmgbagdohdnhkik
  "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcBHwzDvyBQ6bDppkIs9MP4ksKqCMyXQ/A52JivHZKh4YO/9vJsT3oaYhSpDCE9RPocOEQvwsHsFReW2nUEc6OLLyoCFFxIb7KkLGsmfakkut/fFdNJYh0xOTbSN8YvLWcqph09XAY2Y/f0AL7vfO1cuCqtkMt8hFrBGWxDdf9CQIDAQAB",
  "name": "Native Messaging Example",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Send a message to a native application.",
  "app": 
    "launch": 
      "local_path": "main.html"
    
  ,
  "icons": 
    "128": "icon-128.png"
  ,
  "permissions": [
    "nativeMessaging"
  ]

请给我一些建议.. 非常感谢

【问题讨论】:

你试过阅读这张 Stack Overflow 票吗? ***.com/questions/27643892/… 或 ***.com/questions/27643892/… 请阅读this post,我曾经参考过,并成功建立了扩展和原生应用之间的连接 【参考方案1】:

您不能使用标准输出,因为它是 Chrome.exe 的子进程。 文件写入是可能的。去做吧。

【讨论】:

【参考方案2】:

这是正确的.json


  "name": "com.google.chrome.example.echo",
  "description": "Chrome Native Messaging API Example Host",
  "path": "native-messaging-example-host.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
  ],
  "permissions": [
    "nativeMessaging"
  ]

【讨论】:

如何在 allowed_origins 中计算这个扩展 ID?到目前为止,我手动安装了扩展,转到它的设置并将扩展 ID 从那里复制到我的本地消息传递清单中。有没有更好的办法?

以上是关于如何在 chrome 扩展本机消息传递和 c# 应用程序之间发送/接收消息的主要内容,如果未能解决你的问题,请参考以下文章

为 Chrome 扩展指定本机消息传递主机

如何使用本机消息传递主机调试未打包的 Microsoft Edge 扩展?

与本机消息传递主机通信时出错(chrome 令牌签名)

本机消息传递主机 chrome-token-signing

Chrome 扩展的原生消息传递

chrome 扩展通过共享本地存储将多条消息传递到外部站点