1
votes

I created a Chrome extension and use Native Messaging to connect to a C++ native application.

But for every message that the Chrome extension sends to the native host, a new host exe instance is created. I think it is not efficient because I send many messages to the host.

Is there a long-lived connection method between a Chrome extension and a native messaging host?

1
How about including your code to connect to the native host? - Xan

1 Answers

1
votes

If you are sending the messages with chrome.runtime.sendNativeMessage, or create a new Port object with chrome.runtime.connectNative for every message, then yes, it's inefficient.

The purpose of chrome.runtime.connectNative is to create and maintain open a message Port, which you can reuse. As long as your native host behaves in a manner Chrome expects and doesn't close the connection itself, it will be a long-lived connection.

function connect(messageHandler, disconnectHandler){
  var port = chrome.runtime.connectNative('com.my_company.my_application');
  if(disconnectHandler) { port.onDisconnect.addListener(disconnectHandler); }
  if(messageHandler) { port.onMessage.addListener(messageHandler); }
  return port;
}

var hostPort = connect(/*...*/);
port.postMessage({ text: "Hello, my_application" });

// Goes to the same instance
port.postMessage({ text: "P.S. I also wanted to say this" });

// If you want to explicitly end the instance
port.disconnect();