问题
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