I am writing a Chrome Extension which communicates with a native application via Native Messaging.
In my background script I’ve included the following to send a string to the native application:
let port = chrome.runtime.connectNative('com.camou')
console.log(port)
port.postMessage({ text: "invisible" })
port.onMessage.addListener(function (msg) {
console.log('Received' + msg);
});
In my native C# application, I’ve included the following:
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
_ = NativeMethods.SetConsoleMode(NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE), NativeMethods.ENABLE_BINARY_MODE);
_ = NativeMethods.SetConsoleMode(NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), NativeMethods.ENABLE_BINARY_MODE);
}
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
// Convert the 4 bytes to an integer (message length)
if (BitConverter.IsLittleEndian)
{
length = BitConverter.ToInt32(bytes, 0);
}
// Ensure the message length does not exceed 1024*1024
if (length > 1024 * 1024)
{
// Print error message to stderr
Console.Error.WriteLine("Message length exceeds maximum allowed size.");
return;
}
byte[] messageBytes = new byte[length];
int bytesRead = 0;
while (bytesRead < length)
{
int read = stdin.Read(messageBytes, bytesRead, length - bytesRead);
if (read == 0)
{
Console.Error.WriteLine("Unexpected end of stream.");
return;
}
bytesRead += read;
}
// Convert bytes to string using UTF-8 encoding
string input = Encoding.UTF8.GetString(messageBytes);
Console.WriteLine("Received message: " + input);
SendResponseToChrome("Hello from native app!");
I’ve registered the native application and the native application starts up when the port.postMessage is called but with an error “Unchecked runtime.lastError: Error when communicating with the native messaging host.”.
I’ve looked at previous answers (e.g. How to get Chrome Native Messaging to Listen to application?) and tried to mimic what other posters are doing, but they somehow do not work for me. Please let me know if you’re able to spot where I’ve gone wrong.
I gather from the error message that I’ve made a mistake in my C# application (particularly when trying to parse the message from the background script) but I can’t identify the error specifically.
Thanks!