Native Messaging Host Protocol for Browser Extensions (Chrome, Firefox)
#!/home/s/.nvm/versions/node/v8.11.2/bin/node
// Might be good to use an explicit path to node on the shebang line
// in case it isn't in PATH when launched by Chrome/Firefox
var sendMessage = require('native-messaging')(handleMessage)
function handleMessage (req) {
if (req.message === 'ping') {
sendMessage({message: 'pong', body: 'hello from nodejs app'})
}
}chrome.runtime.connectNativereturns aPortthat can be used to establish persistent connection between the browser and the native app- the Port's
disconnectmethod can be used to disconnect from the native app - the native app can use the OS's machinery to kill its own process at any time
chrome.runtime.sendNativeMessagecan be used to send single message to the native app, useful with non persistent background pages- single native app can communicate with multiple browser extensions
- single browser extension can communicate with multiple native apps
- Add
nativeMessagingpermission to themanifest.jsonfile of your extension - Load the extension to get its ID generated
- Put the
native.messaging.example.jsonin~/.config/google-chrome/NativeMessagingHosts/or~/.mozilla/native-messaging-hosts/
- The name of the file should be identical to the
namefield specified in that file - Only dots
.are allowed as delimiters in the file name - The
pathkey should be absolute path to your nodejs scriptexample.js - Chrome - the
allowed_originskey should contain the extension's ID loaded in step 2 - Firefox - the
allowed_extensionskey should contain the extension's ID specified in itsmanifest.jsonfile
- Make sure that
example.jsis executablechmod 755 - Make sure nodejs is reachable from the shebang line in
example.js - Use the
namespecified innative.messaging.example.jsonto connect to the native app from the extension's background pagebackground.js
Note that the install location for the
native.messaging.example.jsondiffers for each OS and browser. In case you plan to support multiple platforms, it's best to use install script. Here is an example of such script.
| Topic | Chrome | Firefox |
|---|---|---|
| Native Messaging Host Protocol | link | link |
| chrome.runtime.connectNative | link | link |
| Port | link | link |
| chrome.runtime.sendNativeMessage | link | link |
| host.json location | link | link |
| official example | link | link |