Native Messaging

Write by Alan Yang

----------------------------------------------

这篇文章是为了解决chrome extentions与native application进行通信,以及将extentions的内容通过exe程序保存到本地。

需要完成的任务可以拆分为三个:

1、编写一个chrome插件

2、用C/C++编写一个exe程序

3、通过json配置连接chrome插件与exe程序

一、chrome插件

先学会制作一个helloworld的chrome简单插件,然后根据与本地应用通信的原则,编写相应的js文件。如:background.js

var port = chrome.runtime.connectNative('com.my_company.my_application');
port.onMessage.addListener(function(msg) {
  console.log("Received" + msg);
});
port.onDisconnect.addListener(function() {
  console.log("Disconnected");
});
port.postMessage({ text: "Hello, my_application" });

源码详见:connectNative文件夹

二、exe程序

根据与chrome插件通信的原则,编写最简单的可通信与保存文件的exe文件。

#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在一个独立的进程中开启每一个本地消息传递主机,用标准输入stdin和标准输出stdout与之进行通信。

源码详见:cpp文件夹

三、连接配置

编写json文件进行相应的连接配置:manifest.json

{
  "name": "com.my_company.my_application",
  "description": "My Application",
  "path": "D:\\nodejs_workspace\\simpleServer\\nativeMessage\\nativeConsole.exe",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://nmhjjegieimjfecjkbcndhikmghloojp/"
  ]
}
name:任意,但需要在window上进行registry key。

具体步骤为:

1、点击Start后,键入regedit,然后点击Enter。

2、将此位置下的默认的key值设置为:manifest.json的路径。

位置:HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.my_company.my_application

Tip:路径设置要特别注意:

若路径为:D:\nodejs_workspace\simpleServer\nativeMessage\manifest.json

则需要将key的默认值设置为:D:\\\\nodejs_workspace\\\\simpleServer\\\\nativeMessage\\\\manifest.json

description:任意

path:设置为C++程序本地应用的全路径,如:nativeConsole.exe的全路径,用于连接插件和本地应用。注意path的\\

type:标准io

allowed_origins:可连接本地消息主机的chrome插件编号列表,用于连接插件和本地应用。

源码详见:nativeMessage文件夹

一般会将exe程序和连接所用的json文件放在同一个文件夹下,例如:

在D:\nodejs_workspace\simpleServer\nativeMessage有manifest.json与nativeConsole.exe。

而chrome插件则安装到chrome浏览器中。














  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值