Detecting that the peer's browser was closed in a webrtc videochat Detecting that the peer's browser was closed in a webrtc videochat javascript javascript

Detecting that the peer's browser was closed in a webrtc videochat


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!            }        }    }});


I am using a solution like this:

const connection = new RTCPeerConnection(configuration);connection.onconnectionstatechange = () => {    const connectionStatus = connection.connectionState;    if (["disconnected", "failed", "closed"].includes(connectionStatus)) {        console.log("disconnected");    }};