Chrome 小工具: 啓動本地應用 (Native messaging)

最近遇到一個新的問題。須要使用Chrome 插件, 從咱們對咱們當地的一個網站之一啓動C#應用,同時經過本申請值執行不一樣的操做。javascript

在這裏記錄下解決的過程。以便之後查找html


首先咱們需要新建一個google的插件 這個插件包括了三個文件java

manifest.json(名字不可改, 建插件必須文件),background.js(文件名稱可改, 後臺文件),content.js(content script文件 負責與站點頁面交互)web

首先咱們來看看manifest.json 這個文件chrome

<span style="font-family:SimSun;font-size:18px;">{
	"name" : "FastRun",
	"version" : "1.0.1",
	"description" : "Launch APP ",
	"background" : { "scripts": ["background.js"] },

	"permissions" : [
		"nativeMessaging",
		"tabs",
		"http://xxx/*"
	],
	"content_scripts": [
    {
      "matches": ["http://xxx/*"],
      "js": ["content.js"]
    }
	],
	"minimum_chrome_version" : "6.0.0.0",
	"manifest_version": 2
}</span>

裏面的premissions很重要, 他表示咱們的插件在什麼條件執行, "nativeMessaging" 表明要在這個插件中贊成調用這樣的方法json

 "xxx"填入你想要的加載的網址 app

"content_scripts" 中"xxx" 表示在什麼網頁下執行咱們與界面交互的script.post


再來看看後臺文件網站

background.js
google

var port = null; 
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
     if (request.type == "launch"){
       	connectToNativeHost(request.message);
    }
	return true;
});


//onNativeDisconnect
function onDisconnected()
{
	console.log(chrome.runtime.lastError);
	console.log('disconnected from native app.');
	port = null;
}

function onNativeMessage(message) {
	console.log('recieved message from native app: ' + JSON.stringify(message));
}

//connect to native host and get the communicatetion port
function connectToNativeHost(msg)
{
	var nativeHostName = "com.my_company.my_application";
	console.log(nativeHostName);
 	port = chrome.runtime.connectNative(nativeHostName);
	port.onMessage.addListener(onNativeMessage);
	port.onDisconnect.addListener(onDisconnected);
	port.postMessage({message: msg});	
 } 


在這個文件中有兩個方法很重要 

chrome.runtime.onMessage.addListener

connectToNativeHost

先來看第一個方法。

是一個響應事件。當接收到類型爲"launch"的消息時, 調用 connectToNativeHost方法並傳入數據。

com.my_company.my_application

這個是咱們以後需要註冊在Regestry和Native Messaging裏面的名字 以後會講到。

runtime.connectNative這種方法鏈接咱們的Native Messaging而後利用 postMessage 去發送咱們要的信息給咱們的本地應用

固然這裏咱們可以替換爲 sendNativeMessage 直接給本地應用傳值詳見

https://developer.chrome.com/extensions/runtime#method-connectNative

咱們在來看看ContentScript: content.js這個文件

 

<span style="font-family:SimSun;"><span style="font-size:18px;">var launch_message;
document.addEventListener('myCustomEvent', function(evt) {
chrome.runtime.sendMessage({type: "launch", message: evt.detail}, function(response) {
  console.log(response)
});
}, false);</span><strong>
</strong></span>
很是easy, 響應了一個頁面中的事件"myCustomEvent", 同一時候公佈一個消息給咱們的後臺文件background.js,這個消息包括了消息標示 "launch" 和 咱們要傳的值 evt.detail

關於Content Script 的信息 詳見 https://developer.chrome.com/extensions/content_scripts

到這裏咱們的google插件部分就作好了

別忘了在Chrome 插件裏開啓開發人員模式 並載入這個插件

-------------------------------------切割線-------------------------------------


咱們在來看看 Native Messaging 部分 咱們再建一個 json 文件 我這裏也叫作manifest.json(名字可以不是這個) 存在了我本地C:/Native文件夾下

<span style="font-family:SimSun;font-size:18px;">{
	"name": "com.my_company.my_application",
	"description": "Chrome sent message to native app.",
	"path": "C:\\MyApp.exe",
	"type": "stdio",
	"allowed_origins": [
		"chrome-extension://ohmdeifpmliljjdkaehaojmiafihbbdd/"
	]
}</span>

這裏咱們定義了 Native Messaging 的名字, 在path中定義了咱們要執行的本地應用程序, allowed_origins 中長串的字符是咱們插件的id 可以在安裝插件後從google chrome 插件裏看到(安裝插件 可以在chrome中插件開啓開發人員模式並加載咱們以前的插件文件包)


完畢這步之後咱們需要在WIndows 註冊表 中增長google 項目詳細例如如下:

執行-> Regedit -> HKEY_Current_User->Software->Google->Chrome->新建一個叫NativeMessagingHosts的項->新建一個叫com.my_company.my_application的項,  同一時候在這個項裏默認值設置爲咱們Native Messaging 的 位置 C:\\Native\\manifest.json


這樣咱們就完畢了NativeMessaging的設置

-------------------------------------我是切割線-------------------------------------

咱們再來看看這個插件怎樣和咱們的站點交互

先建一個簡單的網頁內容例如如下

<span style="font-family:SimSun;font-size:18px;"><!DOCTYPE HTML>

<html>
<head>
<script>
function startApp() {
	var evt = document.createEvent("CustomEvent");
	evt.initCustomEvent('myCustomEvent', true, false, "im information");
	// fire the event
	document.dispatchEvent(evt);
}

</script>
</head>
<body>

<button type="button" onClick="startApp()" id="startApp">startApp</button>
</body>
</html>
</span>

裏面有一個簡單的button, 這個button會啓動方法, 新建一個名叫"myCustomEvent"的事件, 同一時候附帶有咱們要傳的信息, 並公佈這個事件。 這樣咱們插件中的Content.js 就可以接收並響應這個事件了!

-------------------------------------我是切割線-------------------------------------

咱們最後再來看看C#程序, 隨便作一個很easy的程序, 放到了

C://MyApp.exe這裏

在Main裏面 咱們可以增長如下這種方法, 利用Console.OpenStandardInput這個 咱們可以接收到由頁面傳到咱們應用的值並進行咱們想要的一些操做, 在這裏咱們用一個log4net 記錄咱們程序執行狀況

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace MyApp
{
    static class Program
    {
        public static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        [STAThread]
        static void Main(string[] args)
        {
            
            if (args.Length != 0)
            {
                string chromeMessage = OpenStandardStreamIn();
                log.Info("--------------------My application starts with Chrome Extension message: " + chromeMessage + "---------------------------------");
	        }
	    }

        private static string OpenStandardStreamIn()
        {
            //// We need to read first 4 bytes for length information
            Stream stdin = Console.OpenStandardInput();
            int length = 0;
            byte[] bytes = new byte[4];
            stdin.Read(bytes, 0, 4);
            length = System.BitConverter.ToInt32(bytes, 0);

            string input = "";
            for (int i = 0; i < length; i++)
            {
                input += (char)stdin.ReadByte();
            }

            return input;
        }
    }
}


 

點擊咱們在頁面上增長的button, 而後檢查log文件:


2014-07-30 09:23:14,562 [1] INFO  MyApp.Program ----------------------------------------My application starts with Chrome Extension message: {"message":"im information"}---------------------------------




最後一張圖總結下整個過程


假設想要在安裝咱們本地軟件時安裝這個插件, 咱們需要把咱們的插件先公佈到Chrome web store上詳見https://developer.chrome.com/extensions/external_extensions 

我將不贅述

相關文章
相關標籤/搜索