peers / peerjs

Simple peer-to-peer with WebRTC.
https://peerjs.com
MIT License
12.48k stars 1.43k forks source link

Problem with web page leaving handler on the Peer connection #918

Closed kode-git closed 2 years ago

kode-git commented 2 years ago

Hi, I am working with PeerJS on a simple game in javascript. I didn't implement the PeerJS Server because I used the default one. (No option specified about the host on the Peer init). Anyway, I had some troubles with the peer disconnection handler on the web page closing:

If I tried to close a web page on a connected peer, it is not notified on other peers with the on('close') or on('disconnected') event listener. It is possible to add this feature? Because web browsers can't correctly handle web page closing and peer.destroy() can't correctly work.

afrokick commented 2 years ago

Just subscribe to RTCPeerConnection.onconnectionstatechange event like:

    const call = ...

    call.peerConnection.onconnectionstatechange = () => {
      if (!call) return;

      const state = call.peerConnection.connectionState;

      log(`connectionStateChanged:${state}`);

      switch (state) {
        case 'failed':
          // do something
          break;
        case 'closed':
          // do something 
          break;
      }
    };