demo.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* eslint-env browser */
  2. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  3. // SPDX-License-Identifier: MIT
  4. const pc = new RTCPeerConnection({
  5. iceServers: [
  6. {
  7. urls: 'stun:stun.l.google.com:19302'
  8. }
  9. ]
  10. })
  11. const log = msg => {
  12. document.getElementById('logs').innerHTML += msg + '<br>'
  13. }
  14. const sendChannel = pc.createDataChannel('foo')
  15. sendChannel.onclose = () => console.log('sendChannel has closed')
  16. sendChannel.onopen = () => console.log('sendChannel has opened')
  17. sendChannel.onmessage = e => log(`Message from DataChannel '${sendChannel.label}' payload '${e.data}'`)
  18. pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
  19. pc.onicecandidate = event => {
  20. if (event.candidate === null) {
  21. document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
  22. }
  23. }
  24. pc.onnegotiationneeded = e =>
  25. pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
  26. window.sendMessage = () => {
  27. const message = document.getElementById('message').value
  28. if (message === '') {
  29. return alert('Message must not be empty')
  30. }
  31. sendChannel.send(message)
  32. }
  33. window.startSession = () => {
  34. const sd = document.getElementById('remoteSessionDescription').value
  35. if (sd === '') {
  36. return alert('Session Description must not be empty')
  37. }
  38. try {
  39. pc.setRemoteDescription(JSON.parse(atob(sd)))
  40. } catch (e) {
  41. alert(e)
  42. }
  43. }
  44. window.copySDP = () => {
  45. const browserSDP = document.getElementById('localSessionDescription')
  46. browserSDP.focus()
  47. browserSDP.select()
  48. try {
  49. const successful = document.execCommand('copy')
  50. const msg = successful ? 'successful' : 'unsuccessful'
  51. log('Copying SDP was ' + msg)
  52. } catch (err) {
  53. log('Unable to copy SDP ' + err)
  54. }
  55. }