Chrome NativeClient创建 (转)

Chrome NativeClient创建

demo目标是让chrome扩展启动本地exe

 

1创建一个名叫nativeMsgDemo的控制台程序

#include <Windows.h>

 

#include <iostream>

#include <string>

#include <fstream>

using namespace std;

 

bool RecieveMsgFromChrome();

 

int main(int argc, char* argv[])

{

         while(1)

         {

                   Sleep(300);

                   if (!RecieveMsgFromChrome())

                            break;

         }

         return 1;

}

生成的exe是nativeMsgDemo.exe

2. 扩展要写入的内容

在扩展的background.js中写入内容,这样chrome扩展支持nativeclient消息响应

var port = chrome.runtime.connectNative('com.wudi.chrome.namsg.yunzhou'); 

port.onMessage.addListener(function(msg) { 

  console.log("Received" + msg); 

}); 

port.onDisconnect.addListener(function() { 

  console.log("Disconnected"); 

}); 

port.postMessage({ text: "Hello, my_application" }); 

3. chrome NativeMessagingHosts注册表文件

com.wudi.chrome.namsg.yunzhou写入注册表

HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.wudi.chrome.namsg.yunzhou

通过这个注册表找到.json文件的路径

D:\projects\NativeMsgDEmo\output\com.wudi.chrome.namsg.yz-win.json,

在这个文件中保存了chrome.runtime.connectNative真正关联通讯的exe,文件内容如下:

{

  "name": "com.wudi.chrome.namsg.yunzhou",

  "description": "Chrome Native Messaging For yuzhou",

  "path": "nativeMsgDemo.exe",

  "type": "stdio",

  "allowed_origins": [

    "chrome-extension://hohonaplgfolmdaaafoddgbiakognoal/"

  ]

}

一般会将.json文件和.exe文件放在同一个目录下,方便找到,如下图:

 

然后让chrome加载我们的扩展,backgroud.html会加载backgroud.js,background.js中的chrome.runtime.connectNative会获取到和chrome通讯的exe,这种进程间通讯方式是标准的输入输出。

4. nativeClient .exe寻找流程

1. 通过background.js 中的var port =

chrome.runtime.connectNative('com.wudi.chrome.namsg.yunzhou'); 

查找注册表项HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts中的

com.wudi.chrome.namsg.yunzhou

2. 通过上述注册表项找到com.wudi.chrome.namsg.yz-win.json文件

3. 在com.wudi.chrome.namsg.yz-win.json文件中指定了连接输入输出的exe

 

 

 

posted @ 2016-04-13 17:51  Atlas_wu  阅读(1342)  评论(0编辑  收藏  举报