c# - Chrome 原生消息

标签 c# google-chrome chrome-native-messaging

我正在开发“Chrome Native Messaging”的示例应用程序。我按照网站上提到的步骤完成了所有设置。我也能够运行应用程序,但是我没有收到来自 native 应用程序的响应消息。当我第一次开始扩展时,我收到了响应消息。

Downloaded sample from here

当我从浏览器 native 应用程序发送消息时没有响应,请检查下图

enter image description here

C#代码如下

static void Main(string[] args)
    {
        string message = "test message from native app.";
        OpenStandardStreamOut(message);
        while (OpenStandardStreamIn() != null || OpenStandardStreamIn() != "")
        {
            OpenStandardStreamOut("Received to Native App: " + OpenStandardStreamIn());
            OpenStandardStreamOut("Recieved: " + OpenStandardStreamIn());
        }
    }

    private static string OpenStandardStreamIn()
    {
        //// We need to read first 4 bytes for length information
        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;
    }

    private static void OpenStandardStreamOut(string stringData)
    {
        //// We need to send the 4 btyes of length information
        string msgdata = "{\"text\":\"" + stringData + "\"}";
        int DataLength = msgdata.Length;
        Stream stdout = Console.OpenStandardOutput();
        stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
        //Available total length : 4,294,967,295 ( FF FF FF FF )
        Console.Write(msgdata);
    }

manifest.json如下

  {"name": "com.example.native",
  "description": "Native support for Chrome Extension",
  "path": "NativeApp.exe",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
  ],
  "permissions": [
    "nativeMessaging"
  ]
}

有些地方我觉得我们没有收到来自本地主机的响应,因为我已经在浏览器中的以下代码中添加了调试点,但没有被命中

function onNativeMessage(message) {

appendMessage("收到消息:"+ JSON.stringify(message) + "");

我错过了什么吗?

最佳答案

我遇到了同样的问题。确保您发送的消息是有效的 JSON。在我的例子中,主机收到的值是 "some value" 带双引号。当它被连接起来生成 msgdata 变量时,它创建了无效的 JSON。

关于c# - Chrome 原生消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423407/

相关文章:

c# - 页面加载时在 WebBrowser 中显示滚动条

c# - 有没有办法达到通过引用传递 "event"的效果?

javascript - 为什么我的 Manifest.json 显示 "Page does not work offline"

google-chrome - Chrome 中的 CSS3 box-shadows 非常慢

npapi - Edge 中 Chrome native 消息传递的等效项

macos - 使用 Xamarin Mac、C# 的跨浏览器、跨平台 native 消息传递

c# - 如何使用 Newtonsoft.JSON JObject 获得一致的日期时间值

c# - 不确定如何模拟 INancyModule.View 方法?

internet-explorer - 是否可以检测用户何时切换标签?

c - 将数据从 Host App 发送到 Chrome 扩展