async tab close

Simple WebRTC chat in two tabs

by jib1

HTML

Open in two windows and click <button id="button">Connect</button> in one, then close either.<br>
<div id="div"></div>
<script src="https://jan-ivar.github.io/localSocket/localSocket.js"></script>

JavaScript

const console = { log: msg => div.innerHTML += msg + "<br>" };

const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("chat", {negotiated: true, id: 0});

dc.onclose = () => console.log("remote closed");

pc.oniceconnectionstatechange = e => console.log(pc.iceConnectionState);
pc.onicecandidate = ({candidate}) => sc.send({candidate});
button.onclick = async e => {
  await pc.setLocalDescription(await pc.createOffer());
  sc.send({description: pc.localDescription});
};

const sc = new localSocket();
sc.onmessage = async ({data: {description, candidate}}) => {
  if (description) {
    await pc.setRemoteDescription(description);
    if (description.type == "offer") {
      await pc.setLocalDescription(await pc.createAnswer());
      sc.send({description: pc.localDescription});
    }
  } else if (candidate) await pc.addIceCandidate(candidate);
}