Modern WebRTC tab hangup demo

Simple WebRTC test in two tabs

by jib1

HTML

<video id="v" height="120" width="160" autoplay></video><br>
<button id="call">Call!</button>
<button id="hangup">Hangup!</button><br><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="https://rawgit.com/jan-ivar/localSocket/master/localSocket.js"></script>

JavaScript

var newPeer = () => {
  var pc = new RTCPeerConnection();
  pc.ondatachannel = e => e.channel.onclose = stop;
  pc.onaddstream = e => v.srcObject = e.stream;
  pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
  pc.onicecandidate = e => send({ candidate: e.candidate });
  pc.onnegotiationneeded = e => Promise.resolve() // <-- Bug 1175609
    .then(() => pc.createOffer().then(d => pc.setLocalDescription(d)))
    .then(() => send({ sdp: pc.localDescription })).catch(log);
  return pc;
};
var pc = newPeer();

call.onclick = e =>
  navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => (pc.addStream(v.srcObject = stream),
                   pc.createDataChannel("close").onclose = stop))
  .catch(log);

var stop = e => (v.srcObject.getTracks().forEach(track => track.stop()),
                 v.srcObject = null, pc.close(), pc = newPeer());
hangup.onclick = e => stop();

var sc = new localSocket(), send = obj => sc.send(JSON.stringify(obj));
var incoming = msg => msg.sdp &&
  pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
  .then(() => pc.signalingState == "stable" || pc.createAnswer()
    .then(answer => pc.setLocalDescription(answer))
    .then(() => send({ sdp: pc.localDescription })))
  .catch(log) || msg.candidate &&
  pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
sc.onmessage = e => incoming(JSON.parse(e.data));

var log = msg => div.innerHTML += "<br>" + msg;