Js | 通过Chrome的Native Messaging与本地应用程序交互

简介:前端页面通过js发布事件,并使Chrome拓展程序在接收到事件时调用本地应用程序

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.

核心文件及介绍

  1. manifest.json
    • Chrome插件配置信息文件
    • 可以改名
  2. background.js
    • 核心逻辑文件
    • 可以改名
  3. content.js
    • 接受事件并转发至background.js

核心代码

//manifest.json

{
    "name": "com.my_company.my_application", // background.js里面要调用的host
    "description": "Dhcc imedical lis print config app",
    "path": "C:\\Target.exe", // 要调用的本的应用程序
    "type": "stdio",
    "allowed_origins": [ // 安装完chrome插件的ID
        "chrome-extension://acpcejomihdkopjnnijfmnpdgfkmfhkj/"
    ]
}

通过修改注册表让chrome知道这个json就是com.my_company.my_application的配置文件:

运行 -> Regedit -> HKEY_Current_User -> Software -> Google -> Chrome -> 新建一个叫NativeMessagingHosts的项 -> 新建一个叫com.my_company.my_application的项, 同时在这个项里默认值设置为我们Native Messaging 的位置即这个json文件的位置,如C:\Native\manifest.json

//background.js

var port = null;   
chrome.runtime.onMessage.addListener(  
    function(request, sender, sendResponse) {  
        if (request.type == "launch"){ // 相应事件为launch时调用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"; // 注册表里配置的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.页面传来myCustomEvent时
    console.log(evt);
    chrome.runtime.sendMessage({ // 2.向background.js发送type为launch的信息
    type: "launch", message: evt.detail}, function(response) {  
    });  
}, false);

调用方式

function startApp() {
    var evt = document.createEvent("CustomEvent"); // 新建事件
    evt.initCustomEvent('myCustomEvent', true, false, "TestMessage");
    
    document.dispatchEvent(evt); // 发布事件
}

你可能感兴趣的:(Js | 通过Chrome的Native Messaging与本地应用程序交互)