how to use NativeMessaging to connect to a native application(.exe) ,but don't launch the .exe,just send the message background

廉价感情. 提交于 2019-12-08 06:07:23

问题


enerytime when i click the "send" button(blind the NativeMessaging method),it will launch a new instance , i just want make it only one instance with the connect running correctly,sot that i can send message sustainable. Thanks a lot!

That's my background.js code:

var port = null;
console.log("visited test!");
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
    if (request.type == "launch") {
        console.log("visited 333!");
        connectToNativeHost(request.message);
    }
    return true;
});
// chrome.runtime.onMessage.addListener(function(msg) {
//     console.log("Received" + msg.text);
// });

//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.example.test";
    // console.log(typeof(nativeHostName));
    // console.log(nativeHostName);
    //port = chrome.runtime.connectNative(nativeHostName);
    port = chrome.runtime.sendNativeMessage(nativeHostName,{ message: msg });
    port.onMessage.addListener(onNativeMessage); 
    port.onDisconnect.addListener(onDisconnected);
    port.postMessage({ message: msg });
}   

That's my content.js code:

var launch_message;
document.addEventListener('myCustomEvent', function (evt) {
console.log("visited!");
chrome.runtime.sendMessage({ type: "launch", message: evt.detail }, function (response) {
    console.log(response);
    // console.log("visited here!");
});
}, false);

That's my test HTML file code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Test Communicate with native app</title>
    <script>
        function startApp() {
        var evt = document.createEvent("CustomEvent");  
        evt.initCustomEvent('myCustomEvent', true, false, "im information");  
        // fire the event  
        document.dispatchEvent(evt);  
        console.log("The button was clicked!");
        }  
    </script>
</head>

<body>
    <button type="button" onclick="startApp()" id="startApp">startApp</button>
</body>

</html>

and i write the demo native application use C# language.

来源:https://stackoverflow.com/questions/41155633/how-to-use-nativemessaging-to-connect-to-a-native-application-exe-but-dont-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!