Reputation: 3361
I have managed to connect my extension to our native host:
var pulse_tracker_port = chrome.runtime.connectNative('com.cloudfactory.pulsetracker');
but how do I find out if the connection succeeded or not? The value of 'pulse_tracker_report.name' will always be an empty string no matter if the connection succeeded or not.
I also tried to add listeners to find out if the connection succeeded or not but none of these callbacks are being invoked:
chrome.runtime.onConnect.addListener(function(port)
{
console.log('Connected to "Pulse Tracker" @port: ' + port.name);
});
chrome.runtime.onConnectExternal.addListener(function(port)
{
console.log('Connected to "Pulse Tracker" @port: ' + port.name);
});
BTW this won't be invoked either:
pulse_tracker_port.onConnect.addListener(function(port)
{
console.log('Connected to "Pulse Tracker" @port: ' + port.name);
});
This is what I get when I try to do so:
main.js:26 Uncaught TypeError: Cannot read property 'addListener' of undefined
onConnectExternal works for cross-extension messaging between extensions but looks like it doesn't work for native message hosting. Any help would be appreciated. Thanks
Upvotes: 1
Views: 1139
Reputation: 77541
chrome.runtime.onConnect
and chrome.runtime.onConnectExternal
are not relevant here, since they notify you about incoming connections, not about state of outgoing connections.
pulse_tracker_port
is a Port
object which does not have onConnect
property.
What you need to do is to immediately assign a listener to onDisconnect
event of the port object. If there was a problem with the connection, the listener will be called and chrome.runtime.lastError
will be set:
var pulse_tracker_port = chrome.runtime.connectNative('com.cloudfactory.pulsetracker');
pulse_tracker_port.onDisconnect.addListener(function() {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
});
Otherwise, just try to use it, with .postMessage()
and .onMessage
event. For postMessage
, it will throw an error if the port is disconnected.
Upvotes: 4