github.com/pion/webrtc/v3@v3.2.24/examples/data-channels/jsfiddle/demo.js (about)

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