本插件是基於nativeMessaging
crx打包內容:
1. manifest.json
{ "manifest_version": 2, "name": "demo", "version": "1.0", "description": "simple demo", "browser_action": { "default_icon": "13.png", "default_title": "simple demo", "default_popup": "popup.html" }, "app": { "launch": { "local_path": "popup.html" }}, "permissions": ["nativeMessaging"] }
2. popup.html
<div style="width:200px;"> <p id="label">This is a simple Demo</p> <button id="yes-button">Yes</button> </div> <script type="text/javascript" src="script.js"></script>
3. script.js
document.getElementById('yes-button').addEventListener('click', function(){ var port = chrome.runtime.connectNative('com.google.chrome.demo'); port.onDisconnect.addListener(function() { console.log("Disconnected"); }); port.postMessage({ text: "Hello, my_application" }); port.onMessage.addListener(function(message, sender, sendResponse) { var strs = sendResponse; console.log("Received" +strs+" "+ message.text+" "+ JSON.stringify(message)); }) });
將以上3個文件和一個圖片放到一個文件夾中,進入chrome://extensions/ ,點選開發者模式,選擇,打包擴展程序,即可 將文件夾中的文件打包成crx插件,在將插件拖入,即可完成安裝,只是現在google要求插件必須是由應用商店下載的,所以重新打開google瀏覽器后,這個插件就自動停用,且無法再啟用。
與exe的通信:
1. host.json
{ "name": "com.google.chrome.demo", "description": "Native messaging API host", "path": "D:\\Documents\\Visual Studio 2008\\ProjectsGoogle\\googleDemo\\Release\\googleDemo.exe", "type": "stdio", "allowed_origins": [ "chrome-extension://agajdodbfodoocphplebagbgakgaodjj/" ] }
path:就是你想調用的exe完整路徑
chrome-extension:是你剛才打包的crx安裝后,顯示在界面上的ID
name:鏈接名
2. host.reg
Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.demo] @="D:\\360安全瀏覽器下載\\host.json"
創建注冊表項,com.google.chrome.demo就是剛才的host.json文件中的name,項數據是host.json的路徑
點擊YES 按鍵后,就將exe啟動了,以上即是chrome插件啟動本地exe程序內容
下面寫一下exe中的內容:C++
在OnInitDialog函數中創建線程
HANDLE hThreadcom=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)commandThreadFunc, NULL, 0, NULL);
HANDLE hThreaddata=CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)dataThreadFunc,
NULL,
0,
NULL);
線程處理函數
void commandThreadFunc() { char temp[128]; stringstream strs; while(1) { int ch; if((ch = getchar())!=EOF) { sprintf(temp,"%c",ch); strs<<temp; OutputDebugString(strs.str().c_str()); } }
}
void dataThreadFunc() { while(1) { //send to stdout // Define our message std::string message = "{\"text\": \"This is a response message\"}"; // Collect the length of the message unsigned int len = message.length(); // We need to send the 4 bytes of length information std::cout << char(((len>>0) & 0xFF)) << char(((len>>8) & 0xFF)) << char(((len>>16) & 0xFF)) << char(((len>>24) & 0xFF)); // Now we can output our message std::cout << message; } }
nativeMessaging通信是基於io流的,使用getchar()函數即可接收發送到exe的消息
現在的問題是接收exe發送到chrome插件的有問題,接收不到,在console里看不到,不知道為什么?還有就是nativeMessaging不能進行實時通信,我的需求是本地exe會一直向google瀏覽器發送數據,基本上是100-200包每秒,在瀏覽器上繪制圖形,現在還有待研究中..........