google-chrome-extensionchrome-native-messaging

Why do I not receive any message from Node.JS Native App to my chrome extension?


I am new to chrome native messaging and I want to establish connection between my chrome extension & native app. To clarify, I want to receive messages from my extension, handle them, and send other messages back. But now I'm trying to do it from the one side. Having read all necessary information about it I faced the problem that I my extension keep silence and doesn't log received (potentially) message.

popup.js:

let port = chrome.runtime.connectNative("com.defus.nodejs");

console.log("Waiting for response...");

port.onMessage.addListener((response) => {
  console.log("Received: " + response);
});

manifest.json (appliaction):

{
  "name": "com.defus.nodejs",
  "description": "Run Node.JS",
  "path": "./node.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://myid/"
  ]
}

node.bat:

@echo off
node ./index.js

index.js (nodejs): — How to send message from native app written in Node.js to Chrome extension? (I tried using the links, but some of them, such as https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging$compare?locale=en-US&to=1595872&from=1593969 from comments are broken...)

const header = Buffer.alloc(4);
let message = "something\n";

header.writeUInt32LE(message.length, 0);

process.stdout.write(header);
process.stdout.write(message);

I've registered my application Computer\HKEY_CURRENT_USER\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.defus.nodejs in the regedit & everything works fine if I just launch a random app.

I was trying to use absolute paths, send json objects(and stringified objects) and other various implementations of getting messages from nodejs app, but no solution didn't help. I'm just getting "Waiting for response..." and nothing more. Could anyone provide simple example of how to do what I need, please.


Solution

  • After some other searches It seems I've found the solution to my problem. Here my steps:

    1. Thanks to Hüseyin Yağlı's answer I realized names of the .bat file and the command shouldn't be the same which may lead to script looping.
    2. The message must be JSON stringified.

    If one of the above rules is not followed — the native app won't work. So that I renamed my node.bat with index.bat and tried to send let message = JSON.stringify({ message: "something" }); — and it works.