Modern WebRTC remote call w/chat

Shows modern WebRTC use with cut'n'paste Offer/Answer exchange in Firefox w/chat

by phyreman

HTML

<canvas id="hand" height="120" width="160"></canvas>
<video id="eye" height="120" width="160" autoplay></video>
<br>
<button id="button" onclick="createOffer()">Create Lobby:</button>
<br>
<label for="offer">Lobby Key</label>
<textarea id="offer"></textarea>
<br>
Answer: <textarea id="answer"></textarea><br>
<div id="div"></div>
<br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

CSS

textarea {
  width: 250px;
  height: 150px;
}

JavaScript

var pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] });
pc.onaddstream = e => eye.srcObject = e.stream;
pc.oniceconnectionstatechange = e => console.log(pc.iceConnectionState);

var stream = hand.captureStream(30);
pc.addStream(stream);

function createOffer() {
  pc.createOffer(d => pc.setLocalDescription(d), console.log);
  pc.onicecandidate = e => {
    if (e.candidate) return;
    offer.value = window.btoa(pc.localDescription.sdp);
    offer.select();
    answer.placeholder = "Paste friend's response here";
  };
}

offer.onpaste = e => {
  if (pc.signalingState != "stable") return;
  button.disabled = offer.disabled = true;
  var desc = new RTCSessionDescription({ type:"offer", sdp:window.atob(offer.value) });
  pc.setRemoteDescription(desc)
    .then(() => pc.createAnswer()).then(d => pc.setLocalDescription(d))
    .catch(console.log);
  pc.onicecandidate = e => {
    if (e.candidate) return;
    answer.focus();
    answer.value = window.btoa(pc.localDescription.sdp);
    answer.select();
  };
};

answer.onpaste = e => {
  if (pc.signalingState != "have-local-offer") return;
  answer.disabled = true;
  var desc = new RTCSessionDescription({ type:"answer", sdp:window.atob(answer.value) });
  pc.setRemoteDescription(desc).catch(console.log);
};