Async WebRTC screensharing tab demo
by jib1
HTML
<script src="https://webrtchacks.github.io/adapter/adapter-latest.js"></script>
<button id="capture">Capture screen!</button><br>
<video id="video" width="400" autoplay></video><br>
<div id="div"></div>
<script src="https://jan-ivar.github.io/localSocket/localSocket.js"></script>
JavaScript
const pc = new RTCPeerConnection();
capture.onclick = async () => {
video.srcObject = await navigator.mediaDevices.getDisplayMedia();
for (const track of video.srcObject.getTracks()) {
pc.addTrack(track, video.srcObject);
}
};
pc.ontrack = e => video.srcObject = e.streams[0];
pc.oniceconnectionstatechange = e => div.innerHTML += pc.iceConnectionState + "<br>";
pc.onicecandidate = ({candidate}) => sc.send({candidate});
pc.onnegotiationneeded = async e =>
sc.send({sdp: (await pc.setLocalDescription(), pc.localDescription)});
const sc = new localSocket();
sc.onmessage = async ({data: {sdp, candidate}}) => {
if (sdp) {
await pc.setRemoteDescription(sdp);
if (sdp.type == "offer")
sc.send({sdp: (await pc.setLocalDescription(), pc.localDescription)});
} else if (candidate) await pc.addIceCandidate(candidate);
}