chrome浏览器插件启动本地应用程序
{
“name” : “FastDownload”,
“version” : “1.0.1”,
“description” : “Get file download link fo Point”,
“background” : { “scripts”: [“background.js”] },
“permissions” : [
“nativeMessaging”,
“contextMenus”,
“downloads”,
“tabs”,
“http://*/*”,
“https://*/*”
],
“minimum_chrome_version” : “6.0.0.0”,
“manifest_version”: 2
}
主要的是permissions那一项,因为,添加了”nativeMessaging”这一项是更本地应用程序通信的权限(新版的chrome建议使用这种方式),这样就可以跟本地的应用程序通信了
//Author: match.yangwanqing
//Date: 2014.3.12
//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 = “fastdownload”;//这个后面会讲,是chrome与本地程序通信的桥梁
var downloadID = null;
function getDownloadID(URL)
{
/*chrome.downloads.download({“url”: URL},
function(tmpDownloadID)
{
downloadID = tmpDownloadID;
});*/
//chrome.downloads.cancel({“downloadid”: downloadID});
chrome.downloads.search({“url”: URL},
function(tmpID)
{
alert(tmpID[0].id +
“#” + tmpID[0].totalBytes +
“#” + tmpID[0].mime);
});
}
//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();
//getDownloadID(info.linkUrl);
port.postMessage(info.linkUrl);
};
};
//在浏览器启动时即创建右键菜单,当点击使用Point下载的时候就会调用getClickHandler()函数处理
//信息并与本地程序通信
chrome.contextMenus.create({
“title” : “使用Point下载”,
“type” : “normal”,
“id”: “FastDownloadMenu”,
“contexts” : [“link”],
//”targetUrlPatterns”:[“*://*/*.*”],
“enabled”: true,
“onclick” : getClickHandler()
});
上面说的这么神秘的配置文件就是最开始说到的第二部分:
{
“name”: “fastdownload”,
“description”: “Chrome sent download url to native app.”,
“path”: “/home/yang/QtWork…wnloadPopup/build/home/yang/QtWork…wnloadPopup/build/FastDownloadPopup”,
“type”: “stdio”,
“allowed_origins”: [
“chrome-extension://iebejdppbfamhgbnpoacblnlhpllanfbs/”
]
}
其中,name的内容就是刚才backgroound.js中的那个nativeHostName变量的值
unsigned int length = 0;
//read the first four bytes (=> Length)
//getwchar: receive char from stdin
//putwchar: write char to stdout
for (int i = 0; i < 4; i++)
{
length += getwchar();
}
//read the json-message
fileURL = "";
for (int i = 0; i < length; i++)
{
fileURL += getwchar();
}
//浏览器端传来的数据会有一个双引号引在两端
fileURL = fileURL.mid(1,fileURL.length()-2);
这段代码可以放在main函数中也可以放在其他函数中,发挥你的想象吧!当然读取的方式不止这一种,具体需求因人而异