簡(jiǎn)介:前端頁面通過js發(fā)布事件竞膳,并使Chrome拓展程序在接收到事件時(shí)調(diào)用本地應(yīng)用程序航瞭。
Native Messaging
Extensions and apps can exchange messages with native applications using an API that is similar to the other message passing APIs. Native applications that support this feature must register a native messaging host that knows how to communicate with the extension. Chrome starts the host in a separate process and communicates with it using standard input and standard output streams.
核心文件及介紹
-
manifest.json
- Chrome插件配置信息文件
- 可以改名
-
background.js
- 核心邏輯文件
- 可以改名
-
content.js
- 接受事件并轉(zhuǎn)發(fā)至
background.js
- 接受事件并轉(zhuǎn)發(fā)至
核心代碼
//manifest.json
{
"name": "com.my_company.my_application", // background.js里面要調(diào)用的host
"description": "Dhcc imedical lis print config app",
"path": "C:\\Target.exe", // 要調(diào)用的本的應(yīng)用程序
"type": "stdio",
"allowed_origins": [ // 安裝完chrome插件的ID
"chrome-extension://acpcejomihdkopjnnijfmnpdgfkmfhkj/"
]
}
通過修改注冊(cè)表讓chrome知道這個(gè)json就是com.my_company.my_application的配置文件:
運(yùn)行 -> Regedit -> HKEY_Current_User -> Software -> Google -> Chrome -> 新建一個(gè)叫NativeMessagingHosts的項(xiàng) -> 新建一個(gè)叫com.my_company.my_application的項(xiàng), 同時(shí)在這個(gè)項(xiàng)里默認(rèn)值設(shè)置為我們Native Messaging 的位置即這個(gè)json文件的位置诫硕,如C:\Native\manifest.json
//background.js
var port = null;
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "launch"){ // 相應(yīng)事件為launch時(shí)調(diào)用connectToNativeHost
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) { // 連接com.my_company.my_application并postMessage
var nativeHostName = "com.my_company.my_application"; // 注冊(cè)表里配置的name
port = chrome.runtime.connectNative(nativeHostName);
console.log(port)
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
port.postMessage({message: msg});
}
// content.js
var launch_message;
document.addEventListener('myCustomEvent', function(evt) { // 1.頁面?zhèn)鱽韒yCustomEvent時(shí)
console.log(evt);
chrome.runtime.sendMessage({ // 2.向background.js發(fā)送type為launch的信息
type: "launch", message: evt.detail}, function(response) {
});
}, false);
調(diào)用方式
function startApp() {
var evt = document.createEvent("CustomEvent"); // 新建事件
evt.initCustomEvent('myCustomEvent', true, false, "TestMessage");
document.dispatchEvent(evt); // 發(fā)布事件
}