I've been implementing a webrtc videochat.
Everything is working smoothly except for the case when the peer closes the browser.
I've been trying to handle this event by implementing an onended callback on the remote mediastream. Though, this callback does not seem to ever be called.
How can I detect that the peer's browser has been closed or that the connection was finished on the other side?
You can use the ICE connection status to determine this. If you disconnect one peer it takes some seconds (~5?) to recoginize it, but it works even without a signalling server.
(assuming you called your peer connection pc
)
pc.oniceconnectionstatechange = function() { if(pc.iceConnectionState == 'disconnected') { console.log('Disconnected'); } }
Use signaling gateway to send message to all connected peers that you're leaving; like this:
window.addEventListener('beforeunload', function () { userLeft(); }, false); window.addEventListener('keyup', function (e) { if (e.keyCode == 116) userLeft(); }, false); function userLeft() { signalingGateway.send({ userLeft: true, whoLeft: 'user-id' }); } signalingGateway.on('message', function (signal) { if (signal.userLeft && signal.whoLeft != 'current-user-id') { var relevantPeer = listOfPeers[signal.whoLeft]; if (relevantPeer) { relevantPeer.close(); relevantPeer = null; } var relevantLocalStreams = listOfLocalStreams[signal.whoLeft]; if (relevantLocalStreams.length) { for (var i = 0; i < relevantLocalStreams.length; i++) { if (relevantLocalStreams[i].stop) { relevantLocalStreams[i].stop(); } // it is suggested to stop media tracks instead! } } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With