-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmonitor.js
63 lines (55 loc) · 2.51 KB
/
monitor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
document.addEventListener('DOMContentLoaded', function() {
let portNMH = null;
function log (sMsg) {
const newDiv = document.createElement("div");
newDiv.textContent = sMsg;
document.getElementById('divIncoming').appendChild(newDiv);
}
function nmhSend(oMsg) {
/*
When a messaging port is created using runtime.connectNative Chrome starts native messaging host process and keeps it running until the port
is destroyed. On the other hand, when a message is sent using runtime.sendNativeMessage, without creating a messaging port, Chrome starts a
new native messaging host process for each message. In that case the first message generated by the host process is handled as a response to
the original request, i.e. Chrome will pass it to the response callback specified when runtime.sendNativeMessage is called. All other messages
generated by the native messaging host in that case are ignored.
*/
console.log('About to send ' + JSON.stringify(oMsg));
if (!portNMH) {
console.log('Port not listening'); return;
}
try {
portNMH.postMessage( oMsg );
} catch (e) {
console.log('! postMessage failed! ' + e.message);
}
}
// Send a message on an existing port.
document.getElementById('btnPost').addEventListener('click', function(e) {
nmhSend({ "messagetext": document.getElementById('txtSend').value,
"source": "monitor.html",
"timestamp": new Date().toLocaleTimeString()
});
}, false);
// Send a one-shot message.
//
// TODO: Firefox has a different API signature for |sendNativeMessage|. :(
document.getElementById('btnSend').addEventListener('click', function(e) {
chrome.runtime.sendNativeMessage('com.bayden.nmf.demo', { "messagetext": document.getElementById('txtSend').value,
"source": "monitor.html",
"timestamp": new Date().toLocaleTimeString()
},
(r)=>log('Got one-shot answer:'+JSON.stringify(r)));
}, false);
try {
portNMH = chrome.runtime.connectNative('com.bayden.nmf.demo');
portNMH.onDisconnect.addListener( () => {
log("!!!!NativeMessagingHost.onDisconnect(); " + chrome.runtime.lastError.message);
});
portNMH.onMessage.addListener( (msg) => {
log("[Received Message From NativeHost]: " + JSON.stringify(msg));
});
}
catch (e) {
log('!!! Failed to connect to nativeMessagingHost! ' + e.message + " " + chrome.runtime.lastError.message);
}
});