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:
- A button to call.
- A button to hang up.
- The code creates a session using the JWT generated earlier.
- Then code sets up two event listeners for the call and hang up buttons.
- The first listener will use the
serverCallfunction to make the outbound call to Bob. Your webhook server will receive the user in the request body and route the call. - The second listener will call
hangupto end the call.
- The first listener will use the
Making an app to app voice call
Make a voice call from one web app User to another web app User using the JavaScript Client SDK.
手順
1
Introduction to this task2
Prerequisites3
Create a webhook server4
Create a Vonage Application5
Create the users6
Generate JWTs7
Install Client SDK8
Create the code to make an in-app voice call9
Create the code to receive an in-app voice call10
Run your application11
What's next?