Skip to content

Instantly share code, notes, and snippets.

@oeway
Created May 15, 2021 15:08
Show Gist options
  • Save oeway/74a889f572516ecf104a6e2c85959f5d to your computer and use it in GitHub Desktop.
Save oeway/74a889f572516ecf104a6e2c85959f5d to your computer and use it in GitHub Desktop.
<body>
<button id="button" onclick="connect()">Connect</button>
<div id="div"></div><input id="chat"></input><br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
var pc = new RTCPeerConnection(), dc, enterPressed = e => e.keyCode == 13;
var connect = () => init(dc = pc.createDataChannel("chat"));
pc.ondatachannel = e => init(dc = e.channel);
var init = dc => {
dc.onopen = e => (dc.send("Hi!"), chat.select());
dc.onclose = e => log("Bye!");
dc.onmessage = e => log(e.data);
};
chat.onkeypress = e => {
if (!enterPressed(e)) return;
dc.send(chat.value);
log("> " + chat.value);
chat.value = "";
};
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
pc.onicecandidate = e => send({ candidate: e.candidate });
pc.onnegotiationneeded = e => pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => send({ sdp: pc.localDescription }))
.catch(log);
var sc = new BroadcastChannel('my_channel'), send = obj => sc.postMessage(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;
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment