Native Messaging Host Protocol for Browser Extensions
MIT License
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.connectNative
returns a Port
that can be used to establish persistent connection between the browser and the native appdisconnect
method can be used to disconnect from the native appchrome.runtime.sendNativeMessage
can be used to send single message to the native app, useful with non persistent background pages
nativeMessaging
permission to the manifest.json
file of your extensionnative.messaging.example.json
in ~/.config/google-chrome/NativeMessagingHosts/
or ~/.mozilla/native-messaging-hosts/
name
field specified in that file.
are allowed as delimiters in the file namepath
key should be absolute path to your nodejs script example.js
allowed_origins
key should contain the extension's ID loaded in step 2allowed_extensions
key should contain the extension's ID specified in its manifest.json
fileexample.js
is executable chmod 755
example.js
name
specified in native.messaging.example.json
to connect to the native app from the extension's background page background.js
Note that the install location for the
native.messaging.example.json
differs 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 |