Connecting Chrome apps and extensions with native applications

Tuesday, October 15, 2013

We recently announced the deprecation of NPAPI plug-in support in Chrome. One of the main use cases for NPAPI plugins in Chrome apps and extensions was to connect with native applications installed on the same computer. For example, a native password management application that a user has already installed on the system may want to connect with a Chrome extension to synchronize passwords. To support such use cases without the need for NPAPI, we’ve recently added the Native Messaging API.



To use this API, native applications must register a native messaging host that Chrome apps and extensions can connect to. This is done by installing a special manifest file that defines a name and path to the native messaging host binary, as well as set of app and extension IDs that can connect to it. Once a native messaging host manifest is installed, Chrome apps and extensions can connect to it using simple API:

var port = chrome.extension.connectNative(          "org.chromium.native_messaging_example");

The parameter passed to chrome.extension.connectNative() is the name used to identify the native messaging host. When a native messaging port is created Chrome starts the host in a separate process and communicates with it over the standard input and output streams. The app or extension can send and receive messages from the native application using this simple API:

// Register handler for incoming messages. 
port.onMessage.addListener(function(msg) { 
   console.log("Received " + msg); 
 });

 // Send a message. 
port.postMessage({text: "Hello!"})

It's also possible to send one-off messages without creating a port:

chrome.extension.sendNativeMessage( 
   "org.chromium.native_messaging_example", 
   {messageField: "field value"}, 
   function(response) {
      console.log("Received response" + response); 
   });

For details on how to create and register a native messaging host please refer to the API documentation and check out our sample application, which also includes a simple native messaging host.

The Native Messaging API is available on Windows, OS X and Linux starting from Chrome 29. To learn about other NPAPI alternatives, check out the NPAPI deprecation Chromium wiki page.

Posted by Sergey Ulanov, Software Engineer and Message Dispatcher

Post a Comment