编写chrome插件,调用本地应用程序,并进行通讯(发送信息给应用程序)

开发说明

1、浏览器插件实现
manifest.json文件内容。每个chrome的插件都需要该文件,该文件记录插件的关键信息

{
    "name" : "callapp",
    "version" : "1.0.1",
    "description" : "call local application",
    "background" : { "scripts": ["background.js"] },
    "icons": {
        "16": "16.png",
        "128": "128.png"
    },
    "permissions" : [
    "nativeMessaging",
    "contextMenus",
    "tabs"
    ],
    "minimum_chrome_version" : "6.0.0.0",
    "manifest_version": 2
}

其中由于需要在右键菜单中增加选项,在permissions中增加"nativeMessaging"、"contextMenus"两项;需要和本地程序进行通讯,增加"nativeMessaging"项

maniffest.json所需要的background.js

//Author: jyx
//Date: 2014.10.11
//Description: This is a javaScript file use for handle contextMenus action
//When click the contextMenus, it will sent the infomation to native app

//connect to native app
var port = null;
var nativeHostName = "com.ctrip.ops.mysql.callapp";//chrome与本地程序通信的桥梁,根据该名称进行配置项的寻找。windows下在注册表HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts内寻找,linux下在目录/etc/opt/chrome/native-messaging-hosts/寻找该名称的json文件(本例子为com.ctrip.ops.mysql.callapp.json)

//onNativeDisconnect
function onDisconnected()
{
    //alert("连接到FastDownload服务失败: " + chrome.runtime.lastError.message);
    port = null;
}

//connect to native host and get the communicatetion port
function connectToNativeHost()
{
    port = chrome.runtime.connectNative(nativeHostName);//根据配置文件连接到本地程序
    port.onDisconnect.addListener(onDisconnected);
}

//调用connectToNativeHost函数连接到本地程序,完成后使用port.postMessage函数将纤细传递给应用程序
//将信息写入I/O流与本地程序通信
function getClickHandler() {
      return function(info, tab) { 
        connectToNativeHost();
        port.postMessage(info.linkUrl);
      };
};

//在浏览器启动时即创建右键菜单,在页面链接上右击鼠标会显示该菜单,当点击"start program"的时候就会调用getClickHandler()函数处理
 chrome.contextMenus.create({
    "title" : "start program",
    "type" : "normal",
     "id": "callapp",
    "contexts" : ["link"],
     "enabled": true,
    "onclick" : getClickHandler()
});

程序中nativeHostName需要特殊说明,正是通过该变量,chrome的插件找到调用本地程序的配置
本文的实验环境为windows7,在注册表的HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts中创建对应的项,注册表导出内容如下Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.ctrip.ops.mysql.callapp]
@="D:\\temp\\chromeExtension\\callapp\\callapp.json"

linux下参考http://match-yang.blog.163.com/blog/static/2109902542014319103739996/

2、浏览器调用配置

callapp.json
该文件的路径保存在注册表的HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.ctrip.ops.mysql.callapp项内

{
    "name": "com.ctrip.ops.mysql.callapp",
    "description": "Chrome call native app and sent message to app.",
    "path": "C:\\MyApp.exe",
    "type": "stdio",
    "allowed_origins": [
        "chrome-extension://imcfacgnnkhdheiajocckejfmeiokgol/"
    ]
}

3、本地应用程序例子

使用C#进行开发,C++参考http://match-yang.blog.163.com/blog/static/2109902542014319103739996/

using System;
using System.IO;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            log2file("--------------------program start at " + DateTime.Now.ToString() + "--------------------");
            if (args.Length != 0)
            {
                for (int i = 0; i < args.Length; i++)
                    log2file("arg " + i.ToString() + args[i]);

                string chromeMessage = OpenStandardStreamIn();
                log2file("--------------------My application starts with Chrome Extension message: " + chromeMessage + "---------------------------------");
            }
            log2file("--------------------program end at " + DateTime.Now.ToString() + "--------------------");
        }
        static void log2file(string s)
        {
            FileStream fs = new FileStream(@"c:\test.log", FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(s);
            sw.Close();
            fs.Close();
        }

        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;
        }
    }
}

说明:
background.js代码根据如下链接,进行了一些非框架性的修改,主要是注释,不过还是修改了一下author
http://match-yang.blog.163.com/blog/static/2109902542014319103739996/

参考:
讲解如何在浏览器的右键菜单中增加
http://my.oschina.net/ruben/blog/92813
讲解调用本地的应用程序
http://match-yang.blog.163.com/blog/static/2109902542014319103739996/
http://blog.csdn.net/talking12391239/article/details/38498557#

 

posted @ 2014-10-11 16:40  惡盈好謙  阅读(8387)  评论(2编辑  收藏  举报