Get started with peerjs CDN

MIT licensed

PeerJS is a simple, lightweight library for real-time peer-to-peer communication between web browsers.

Tags:
  • js
  • WebRTC

Stable version

Copied!

How to start using peerjs CDN


<!DOCTYPE html>
<html>
<head>
    <title>Get started with peerjs CDN - cdnhub.io</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/simple-peer.min.js"></script>
    <script src="https://cdn.cdnhub.io/peerjs/1.5.2/peerjs.min.js"></script>
</head>
<body>
    <button id="init">Initiate Call</button>
    <button id="accept">Accept Call</button>
    <div id="output"></div>

    <script>
      const output = document.getElementById('output');
      const initButton = document.getElementById('init');
      const acceptButton = document.getElementById('accept');

      let peer;
      let userVideo;
      let remoteVideo;

      initButton.addEventListener('click', () => {
        const localVideo = document.createElement('video');
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
          .then(stream => {
            localVideo.srcObject = stream;
            userVideo = localVideo;

            peer = new Peer({
              initiator: true,
              trickle: false,
              stream: stream
            });

            peer.on('signal', data => {
              acceptButton.addEventListener('click', () => {
                const remotePeer = new Peer({
                  trickle: false
                });

                remotePeer.on('signal', answer => {
                  peer.signal(answer);
                  remotePeer.on('stream', rStream => {
                    remoteVideo.srcObject = rStream;
                    remoteVideo.play();
                  });
                });

                remotePeer.signal(data);
              });
            });
          })
          .catch(error => {
            output.textContent = 'Error accessing user media: ' + error.name;
          });
      });

      peer.on('stream', stream => {
        remoteVideo.srcObject = stream;
        remoteVideo.play();
      });
    </script>

    <video id="remote" autoplay muted ref="remoteVideo" style="display:none;"></video>
</body>
</html>
Copied!
Copied!
Copied!
Copied!

All versions