Chrome Native Messaging API chrome.runtime.connectNative不是函数

时间:2015-10-09 14:55:48

标签: javascript c# google-chrome google-chrome-app chrome-native-messaging

我希望操作当前位于Chrome标签页上的内容页面,如果以下内容无法做到这一点,那么我需要找到方法来实现这一目标!

嘿所有我试图让这个新的chrome扩展与我的C#程序一起来回传递消息。我已经在stackoverflow上看到了很多代码演示,这主要是我一直在想的,但似乎所有的例子都不适合我。

我遇到的问题是我收到错误:

Connecting to native messaging host com.google.chrome.example.echo
Uncaught TypeError: chrome.runtime.connectNative is not a function

enter image description here

每当我尝试“连接”到端口时。

不知道我做错了什么,因为我在这里跟着其他的tetorials,他们似乎都说它有效......

JS main.js:

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>")
    console.log("Connecting to native messaging host " + hostName);
    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();
});

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"
  ]
}

注册局:

REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "%~dp0com.google.chrome.example.echo-win.json" /f

C#代码:

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

namespace talkWithChromeCSharp
{
    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();
        }
    }
}

com.google.chrome.example.echo-win.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/"
  ]
}

HTML main.html:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <script src='main.js'></script>
</head>
<body>
    <button id='connect-button'>Connect</button>
    <input id='input-text' type='text' />
    <button id='send-message-button'>Send</button>
    <div id='response'></div>
</body>
</html>

我在Visual Studio中的目录结构:

C:\Users\t||||||\Documents\Visual Studio 2012\Projects\talkWithChromeCSharp\talkWithChromeCSharp
   -APP
     |-icon-128.png
     |-main.html
     |-main.js
     |-manifest.json
   -bin
     |-Debug
        |-Newtonsoft.Json.dll
        |-talkWithChromeCSharp.exe
        |-etc etc...
     |-Release
   -obj
   -Properties
   -regs
     |-com.google.chrome.example.echo-win.json
     |-install_host.bat
     |-etc etc...

启动VS调试后,我安装插件并在chrome浏览器上加载main.html文件,然后单击“连接”按钮。那是我收到错误的时候。

我错过了什么?

更新

这是它的正确ID。我保持这种方式,因为我猜测“KEY”是决定ID的原因。

enter image description here enter image description here

4 个答案:

答案 0 :(得分:10)

太多的混乱并没有很好地解释哪些对我有用。 因此,在这里我试图制作一个“白痴证明”的文件。 (请改进此版本)

目标: Windows操作系统,Google Chrome测试版直到50版测试,与原生应用程序通信

第1步:

下载: https://developer.chrome.com/extensions/examples/api/nativeMessaging/app.zip

第2步:

将下载的应用加载到Google Chrome

enter image description here

第3步:

a)添加注册表项

REG ADD "HKLM\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "C:\\run-my-exe\\manifest.json" /f

enter image description here

b)要制作自定义Chrome执行器,请将以下内容复制到C:\ run-my-exe \ run-chrome.bat:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --enable--native-messaging --native-messaging-hosts="com.google.chrome.example.echo=C:\\run-my-exe\\manifest.json"

第4步:主持人

a)将以下内容放到C:\ run-my-exe \ manifest.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/"
  ]
}

b)将以下内容放到C:\ run-my-exe \ native-messaging-example-host.bat

@echo off
cd %windir%\system32
start calc.exe

第5步:我现在如何运行它?

a)使用此脚本打开chrome:C:\\run-my-exe\\run-chrome.bat

chrome中的

b)转到chrome://apps

c)启动

通过图标

enter image description here

不如下:

enter image description here

最终输出:

enter image description here

答案 1 :(得分:2)

您不应该直接打开main.html,而应该通过chrome:// apps /

从Chrome的应用启动器中打开

答案 2 :(得分:1)

小心复制粘贴!

https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging/app/manifest.json

我会假设您获得了清单。 替换&#34;键&#34;用合适的一个

和&#34; allowed_origins&#34;使用您的实际扩展ID而不是示例

中的扩展ID

https://developer.chrome.com/apps/manifest/key

那里可能会有更多的错误,但那些只是我第一次看到的错误。

答案 3 :(得分:1)

由于您使用的是生成exe文件作为输出的C#项目,因此native-messaging-example-host.bat的文件不应该像原始示例那样:

python "%~dp0/native-messaging-example-host" %*

相反,批处理文件应更改如下:

@echo off
Pushd C:\Users\h.aghajani\Desktop\host  /*Path directory of your exe*/
start native-messaging-example-host.exe /*Name of the execution file*/