Async WebRTC tab demo

by jib1

HTML

<script src="https://webrtchacks.github.io/adapter/adapter-latest.js"></script>
<video id="video" height="120" width="160" autoplay></video><br>
<button id="call">Call!</button><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();

call.onclick = async () => {
  const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
  video.srcObject = stream;
  for (const track of stream.getTracks()) {
    pc.addTrack(track, stream);
  }
};

pc.ontrack = ({streams}) => video.srcObject = streams[0];
pc.oniceconnectionstatechange = () => console.log(pc.iceConnectionState);
pc.onicecandidate = ({candidate}) => sc.send({candidate});
pc.onnegotiationneeded = async () => {
  await pc.setLocalDescription(await pc.createOffer());
  sc.send({sdp: pc.localDescription});
}

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