JavaScript

Create the code to receive an in-app voice call

Create another HTML file called client_bob.html.

Add the following code, but make sure you paste the Bob JWT you generated for the user receiving the call in the earlier step as the value for the token constant:

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="./node_modules/@vonage/client-sdk/dist/vonageClientSDK.min.js"></script>
  <style>
    input, button {
      font-size: 1rem;
    }
    #answer {
      display: none;
    }
  </style>
</head>

<body>
  <h1>Inbound App Call (Bob)</h1>
  <p id="notification">Lines are open for calls...</p>
  <br />
  <button id="answer">Answer</button>

  <script>
    const answerButton = document.getElementById("answer");
    const notification = document.getElementById("notification");
    const token = 'BOB_JWT';
    const client = new vonageClientSDK.VonageClient();
    let callId = null;

    client.createSession(token)
      .then((sessionId) => {
        console.log(sessionId);
      })
      .catch((error) => {
        console.error(error);
      });

    client.on('callInvite', (_callId) => {
      callId = _callId;
      notification.textContent = "You are receiving a call";
      answerButton.style.display = "inline";
    });

    client.on('callHangup', (callId, callQuality, reason) => {
      callId = null;
      notification.textContent = "Lines are open for calls...";
      answerButton.style.display = "none";
    });

    // Answer the call.
    answerButton.addEventListener("click", () => {
      client.answer(callId)
        .then(() => {
          console.log("Success answering call.");
          notification.textContent = "You are on a call";
          answerButton.style.display = "none";
        })
        .catch(error => {
          console.error("Error answering call: ", error);
        });    
    });
  </script>
</body>

</html>

This is your client application that uses the Client SDK to receive a voice call from the user Alice.

There are several key components to this code:

  1. A notification box that can be updated with the call status.
  2. A button to answer an inbound call.
  3. The code creates a session using the JWT generated earlier.
  4. The code sets up an event handler. It is fired on an inbound call invite. This in turn sets up a click button event handler which answers the inbound call using the Client SDK method answerCall.
  5. Another event handler is set up to listen for hang up events, this will be fired when the other side of the call hangs up.