Web Based Video Chat Using PeerJS

Introduction

 
PeerJS is a JavaScript library and provides functionality to access WebRTC.
 
WebRTC allows real-time browser-to-browser communication for voice calling and video chat. The user does not need to install any additional plugin or application in order to access WebRTC.
 
WebRTC is supported in the following browsers.
  • Microsoft Edge
  • Google Chrome
  • Mozilla Firefox
  • Opera
Let’s create one simple application that will allow us to video chat; before we start coding you will need peer.js file, you can download that file, also you need an API key in order to access peerjs cloud server. If you want to run this on your own server then you can get code and also you can deploy.
 
Create your account on peerjs.com to get your own API key,
 
peer1.JPG
 
You can check your browser compatibility by writing simple below js:
 
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
 
peer2.JPG
 
getUserMedia allows a web browser to access the camera and microphone and to capture media
  1. // PeerJS object    
  2.     
  3. var peer = new Peer({ key: 'lwjd5qra8257b9' });   
Above code will create a connection with peerjs server, and on connection success with the server it will assign one random unique id, every time when connection established with peerjs server it will return one unique id for each user it would be like phone number, we will use that unique id for establishing a connection with another user.
  1. peer.on('open'function()    
  2. {    
  3.     
  4.     console.log(‘id: ’+peer.id);    
  5.     
  6. });   
We will need another user peer id so we can establish a connection, you can simply run the same code on another browser if you don’t have another pc. But only one browser at a time can stream your webcam.
 
Once you have peer id of another user then just try to connect with that user,
  1. // Initiate a call!    
  2.     
  3. var call = peer.call(‘dest peerid’, window.localStream);   
peer.call and the callback of the call event provide a MediaConnection object. The MediaConnection object itself emits a stream event whose callback includes the video/audio stream of the other peer.
 
Now when we receive a call from another user, we will create an event that will answer to call and display the video:
  1. <video id="their-video" autoplay></video>    
  2.     
  3. <video id="my-video" muted="true" autoplay></video> // Receiving a call peer.on('call', function (call)    
  4.      { // Answer the call automatically call.answer(window.localStream);    
  5.        // Hang up on an existing call if present if (window.existingCall)     
  6.   {     
  7.     window.existingCall.close();    
  8.   }     
  9.   // Wait for stream on the call, then set peer video display     
  10.   call.on('stream'function (stream)     
  11.     {     
  12.     $('#their-video').prop('src', URL.createObjectURL(stream));     
  13.     });     
  14.   // UI stuff     
  15.   window.existingCall = call; $('#their-id').text(call.peer);    
  16. });     
  17. peer.on('error'function (err)     
  18.   {    
  19.   alert(err.message);     
  20.   });     
  21. //To display your own video     
  22. navigator.getUserMedia(    
  23.   {    
  24.     audio: true, video: true    
  25.   }, function (stream)     
  26.   {     
  27.     // Set your video displays     
  28.     $('#my-video').prop('src', URL.createObjectURL(stream)); window.localStream = stream;    
  29.   }, function ()    
  30.   {     
  31.     console.log(‘Failed to access the webcam and microphone.’);    
  32.   });     
  33. //To end the call     
  34. window.existingCall.close();    
  35. //perform something when call ended     
  36. peer.on('close'function() { ... });   
You can also print all connection logs on console, 
  1. var peer = new Peer({key: 'lwjd5qra8257b9'}, 3);   
You can also do instant message through peerjs, do the following for sending message to another user:
  1. var conn = peer.connect('dest-peer-id');    
  2. conn.on('open'function()    
  3. {    
  4.     // Receive messages    
  5.     conn.on('data'function(data)    
  6.     {    
  7.         console.log('Received', data);    
  8.     });    
  9.     
  10.     // Send messages    
  11.     conn.send('Hello !');    
  12. });   
Download an attachment to experience it.
 
Read more articles on JavaScript