Created
October 20, 2018 22:33
-
-
Save zapo/063afe44bb43737b0fe45a3d3f96b97a to your computer and use it in GitHub Desktop.
WebRTC channel communication sample (same browser signaling through localStorage)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const connection = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }); | |
connection.onicecandidate = (e) => { | |
if (e.candidate) { | |
localStorage.setItem('candidate', JSON.stringify(e.candidate)); | |
} | |
}; | |
connection.oniceconnectionstatechange = (e) => { | |
console.log(connection.iceConnectionState); | |
} | |
const channel = connection.createDataChannel('chat', { negociated: true, id: 'very secret' }); | |
channel.onmessage = ({ data }) => console.log(data); | |
window.sendMessage = (message) => { | |
channel.send(message) | |
} | |
async function createOffer() { | |
const offer = await connection.createOffer(); | |
connection.setLocalDescription(offer) | |
localStorage.setItem('offer', JSON.stringify(offer)); | |
} | |
async function createAnswer(offer) { | |
connection.setRemoteDescription( | |
new RTCSessionDescription(offer) | |
); | |
const answer = await connection.createAnswer(); | |
connection.setLocalDescription(answer) | |
localStorage.setItem('answer', JSON.stringify(answer)) | |
} | |
async function acceptAnswer(answer) { | |
connection.setRemoteDescription(new RTCSessionDescription(answer)); | |
}; | |
window.addEventListener('storage', ({ key, newValue }) => { | |
switch(key) { | |
case 'offer': | |
createAnswer(JSON.parse(newValue)); | |
break; | |
case 'answer': | |
acceptAnswer(JSON.parse(newValue)); | |
break; | |
case 'candidate': | |
connection.addIceCandidate(JSON.parse(newValue)); | |
break; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment