0

我正在尝试用于 Chrome 扩展的 Chrome Native Messaging API。

本机应用程序的 Manifest.json:

{
  "name": "app.native",
  "description": "Native Message API Test.",
  "path": "native.exe",
  "type": "stdio",
  "allowed_origins": ["chrome-extension://kembignchdjhopkkcolnamikcenaocdm/"]
}

Windows 注册表值:

HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\app.native=D:\connectNative\manifest.json

我也试过D:\\\\connectNative\\\\manifest.json

我将“nativeMessaging”添加到 Chrome 扩展 manifest.json 中的“权限”中。

本机应用程序 cpp:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char* argv[]) {
    string input = "";
    string message="{\"text\": \"This is a response message\",\"num\": \"three\"}";
    unsigned int len = message.length();
    cout << char(((len>>0) & 0xFF))
         << char(((len>>8) & 0xFF))
         << char(((len>>16) & 0xFF))
         << char(((len>>24) & 0xFF));
    cout << message <<endl;
    getline(cin, input);
    cout << "You entered: " << input << endl;
    ofstream myfile;
    myfile.open ("example.txt");
    myfile << "Writing this to a file.\n";
    myfile << input;
    myfile.close();

    return 0;
}

完成后,我尝试使用我的 Chrome 扩展程序:

var testport = chrome.runtime.connectNative('app.native');
testport.onMessage.addListener(function(msg) {
    console.log("Received" + msg);
});
testport.onDisconnect.addListener(function() {
  console.log("Disconnected");
});

它无法接收任何消息并始终打印“已断开连接”。

我尝试连接到一个不存在的应用程序,它仍然打印“断开连接”,所以我知道这个本机应用程序配置不正确。

谁能指出什么是错的或我错过了什么?

4

2 回答 2

1

默认情况下, cout 是一个文本流,发送 null (作为您大小前 4 个字节的一部分)会提前结束您的文本流。

在 Windows 上,您可以通过更改底层标准输出将 cout 更新为二进制,并且不要忘记刷新...

_setmode(_fileno(stdout), _O_BINARY);   
int len = msg.length();
std::cout << char(len >> 0)
  << char(len >> 8)
  << char(len >> 16)
  << char(len >> 24);

std::cout << msg << std::flush;
于 2016-05-11T09:52:32.953 回答
-1

具有本机参考的工作脚本示例。请注意脚本中稍后在引用中对外部资源的权限nativeMessaging和不直接引用。Manifest.json.js

{
   "background": {
      "scripts": [ "common.js", "filler.js",  "background.js" ]
   },
   "browser_action": {
      "default_icon": "r.png",
      "default_title": "Click this button to show commands"
   },
   "content_scripts": [ {
      "all_frames": true,
      "js": [ "common.js", "content.js", "filler.js" ],
      "matches": [ "http://*/*", "https://*/*", "file:///*" ],
      "run_at": "document_start"
   } ],
   "description": "For Google Chrome",
   "homepage_url": "http://www.app.com",
   "icons": {
      "128": "r.png",
      "16": "r.png",
      "32": "r.png",
      "48": "r.png"
   },
   "key": "???",
   "manifest_version": 2,
   "name": "???",
   "options_page": "options.html",
   "permissions": [ "tabs", "bookmarks", "webRequest", "webRequestBlocking", "nativeMessaging", "downloads", "http://*/*", "https://*/*" ],
   "update_url": "https://clients2.google.com/???/",
   "version": "???"
}
于 2014-04-26T17:05:12.950 回答