Answering a Call

The peerJS framework makes the .on('call') event available to use so let’s use it here.

peer.on('call', function(call) {
    const answerCall = confirm("Do you want to answer?")

Aconst answerCall = confirm("Do you want to answer"): First, let’s prompt the user to answer with a confirm prompt. This will show a window on the screen (as shown in the image) which the user can select “ok” or “cancel”, which maps to a boolean value which is returned. When you press "Call" in your browser, the following prompt should appear:

A browser prompt that asks "Do you want to answer?" with two options: "Cancel" and "Ok"

Since we’re using a confirm prompt to ask the user if they want to answer the call, it’s important that the browser and tab that’s being called be “active” that means the window shouldn’t be minimized and the tab should be on screen and have the mouse’s focus somewhere in the tab. Ideally, you’d create your own modal in HTML which wouldn’t have these limitations.

Let's flesh out this event listener:

peer.on('call', function(call) {
   const answerCall = confirm("Do you want to answer?")

      call.answer(window.localStream) // A
      showConnectedContent(); // B
      call.on('stream', function(stream) { // C
         window.remoteAudio.srcObject = stream;
         window.remoteAudio.autoplay = true;
         window.peerStream = stream;
   } else {
      console.log("call denied"); // D

Acall.answer(window.localStream): if the answerCall is true, then you want to call peerJS’s answer function on the call to create an answer, passing it the local stream.

BshowCallContent: similarly to what you did in the call button event listener, you want to ensure the person being called sees the correct HTML content.

C. Everything in the call.on('stream', function(){...} block is exactly the same as it is in call button’s event listener. The reason you need to add it here too is so that the browser is also updated for the person answering the call.

D. If the person denies the call, we’re just going to log a message to the console.

The code you have now is enough for you to create a call and answer it. Refresh your browsers and test it out. You’ll want to make sure that both browsers have the console open or else you won’t get the prompt to answer the call. Click call, submit the peer ID for the other browser and then answer the call. The final page should look like this:

Two screens side by side both have a cream background with the words 'phone a friend' in bold, dark green font as the heading. 'You're connected.' is immediately below that and 'please use headphones!' and 'You're automatically muted, please unmute yourself!' below that. Following on, a big dark red button with 'Hang up' written in the same cream color of the background.