This template creates a minimal chat room for all the visitors of the site. It uses the Peersockets API to send and receive messages. Traffic is encrypted so that only users who possess the site’s URL can read it.

Source

<!doctype html>
<html>
  <head>
    <link rel="icon" type="image/png" sizes="32x32" href="/thumb.png">
  </head>
  <body>
    <h1>Chat Room</h1>
    <input id="input" placeholder="Enter your message here">
    <div id="output"></div>
    <style>
      body {
        margin: 20px;
        font-family: 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }
      h1 {
        font-weight: 500;
      }
      input, #output {
        font-size: 14px;
        letter-spacing: 0.7px;
        padding: 12px;
        border: 1px solid #ccd;
      }
      input {
        width: 100%;
        box-sizing: border-box;
        outline: 0;
        border-bottom: 0;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
      }
      #output {
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        white-space: pre;
        background: #f3f3f8;
        line-height: 1.4;
      }
      #output strong {
        font-weight: 500;
      }
    </style>
    <script>
      var topic
      var peers = new Set()
      var input = document.querySelector('#input')
      var output = document.querySelector('#output')
      
      setup()
      async function setup () {
        var peerEvents = beaker.peersockets.watch()
        peerEvents.addEventListener('join', e => {
          console.log('join', e)
          peers.add(e.peerId)
          output.innerHTML += `<em>Peer ${e.peerId} has joined</em>\n`
        })
        peerEvents.addEventListener('leave', e => {
          console.log('leave', e)
          peers.delete(e.peerId)
          output.innerHTML += `<em>Peer ${e.peerId} has left</em>\n`
        })

        topic = beaker.peersockets.join('chat')
        input.addEventListener('keydown', e => {
          if (e.keyCode !== 13) return

          output.innerHTML += `<strong>You said:</strong> `
          output.append(`${input.value}\n`)
          var message = new TextEncoder('utf-8').encode(input.value)
          input.value = ''

          for (let peer of peers) {
            console.log('sending to', peer)
            topic.send(peer, message)
          }
        })
        topic.addEventListener('message', e => {
          console.log('message', e)
          output.innerHTML += `<strong>Peer ${e.peerId} says:</strong> `
          output.append(`${new TextDecoder().decode(e.message)}\n`)
        })
      }
    </script>
  </body>
</html>