JavaScript

Create the code to make an in-app voice call

For this tutorial, Alice will be calling Bob.

Create an HTML file called client_alice.html and add the following code, making sure to paste Alice's JWT which you generated 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;
    }
    #call, #hangup {
      display: none;
    }
  </style>
</head>

<body>
  <h1>Outbound App Call (Alice)</h1>
  <button type="button" id="call">Call</button>
  <button type="button" id="hangup">Hang Up</button>

  <script>
    const callButton = document.getElementById("call");
    const hangUpButton = document.getElementById("hangup");
    const token = 'ALICE_JWT';
    const client = new vonageClientSDK.VonageClient();
    let callId = null;

    client.createSession(token)
      .then((sessionId) => {
        console.log("Id of created session: ", sessionId);
        callButton.style.display = "inline";
      })
      .catch((error) => {
        console.error("Error creating session: ", error);
      });

    client.on('legStatusUpdate', (callId, legId, status) => {
      if (status === "ANSWERED") {
        callButton.style.display = "none";
        hangUpButton.style.display = "inline";
      }
      if (status === "COMPLETED") {
        callButton.style.display = "inline";
        hangUpButton.style.display = "none";
      }
    });

    callButton.addEventListener("click", () => {
      console.log("Calling Bob...");
      client.serverCall({ to: 'Bob' })
        .then((_callId) => {
          callId = _callId;
        })
        .catch((error)=>{
          console.error(`Error making call: ${error}`);
        });
    });

    hangUpButton.addEventListener("click", () => {
      console.log("Hanging up...");
      client.hangup(callId)
        .then(() => {
          hangUpButton.style.display = "none";
          callButton.style.display = "inline";
        })
        .catch(error => {
          console.error("Error hanging up call: ", error);
        });                
    });
  </script>
</body>

</html>

This is your client application that uses the Client SDK to make an in-app voice call to the destination user (Bob).

The main features of this code are:

  1. A button to call.
  2. A button to hang up.
  3. The code creates a session using the JWT generated earlier.
  4. Then code sets up two event listeners for the call and hang up buttons.
    1. The first listener will use the serverCall function to make the outbound call to Bob. Your webhook server will receive the user in the request body and route the call.
    2. The second listener will call hangup to end the call.