This question is a continuation of that one, because there hasn't been any answer with Nodejs code in that question, 6 years now.
I use Chrome 79 and Nodejs 13, in windows 10.
I have a Nodejs script(see below) acting as the native messaging host, and a Chrome extension.
I want to send messages from the Nodejs script to my extension.
I know how to receive messages in my Chrome extension - here is its background.js:
var port = chrome.runtime.connectNative('my_messaging_host');
port.onMessage.addListener((message) => {
console.log("Received: " + message);
});
The Nodejs script I have(see below) is the native messaging host. I used as a reference the only Nodejs messaging host code example I could find, from MDN.
I've noticed that this Nodejs code example was added in that MDN wiki page very recently, 10 days ago, and it has issues/needs improvement.
Anyway, I've modified it as follows, but I'm getting the following error from my extension when sending messages: Failed to connect: Error when communicating with the native messaging host
, which, based on the docs indicates an incorrect implementation of the communication protocol in the native messaging host.
So, why is my Nodejs script not working ok?
Could you please give me a working Nodejs host code example?
function sendMessage(msg) {
var buffer = Buffer.from(JSON.stringify(msg));
var header = Buffer.alloc(4);
header.writeUInt32LE(buffer.length, 0);
var data = Buffer.concat([header, buffer]);
process.stdout.write(data);
}
For reference, various native messaging host examples:
- Google Native Messaging docs: in Python.
- MDN Native Messaging docs: in Nodejs and Python 2 & 3,
- as answers to the question mentioned above: in C, C++, C# and Python.