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

标签 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();
});

ma​​nifest.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

最佳答案

太多的困惑,没有很好的解释,这对我来说真的很管用。 因此,在这里我试图制作一个“白痴证明”文档。 (请改进此版本)

目标:Windows 操作系统、Google chrome 直到测试版本 50,与 native 应用程序通信


第 1 步:


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

第 2 步:


将下载的应用加载到谷歌浏览器

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"

第四步:主持


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

b) 在 chrome 中转到 chrome://apps

c)启动

通过图标

enter image description here

不是如下:

enter image description here

最终输出:

enter image description here

关于javascript - Chrome Native Messaging API chrome.runtime.connectNative 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33041396/

相关文章:

javascript - JQuery HTML 避免每个表中的第一行

javascript - AngularJS - 在不删除验证错误的情况下设置原始表单

c# - Hook 事件 Outlook VSTO 在主线程上继续工作

javascript - 打开和关闭 Chrome 扩展

javascript - Google Chrome 用户脚本与扩展?

html - 分页前 : always is freezing print dialog box

javascript - 有没有办法在关闭 ng-multiselect-dropdown 时添加一个功能?

javascript - 自动显示列表的jquery函数

c# - FxCop 静态代码分析 : Treat "DB" (and others) like "Id"

c# - 使用x :Name in MVVM动态添加控件