I'm using the Twilio Video Javascript API to stream and record video content from the browser. The application is built in Nodejs/Express
and I am loading the Twilio API
from a CDN
link in the page. So far I can successfully instantiate a room and record the video on the server with the following code:
function createAndConnectToRoom(roomName) {
Twilio.Video.connect(Token, { name: roomName }).then(room => {
console.log(`Successfully joined a Room: ${room}`);
room.on('participantConnected', participant => {
console.log(`A remote Participant connected: ${participant}`);
});
}, error => {
console.error(`Unable to connect to Room: ${error.message}`);
});
displayLocalVideo();
}
My problem is I am unable to disconnect from the server. Ideally, I'd like to have a big button that disconnects the user and terminates the room. On the Twilio docs, they advise using the following code (the outer function is my own, the inner code is from Twilio
). However, I receive Uncaught ReferenceError: the room is not defined
in the Chrome console when I fire this function with an onclick
event.
function disconnectFromRoom() {
room.on('disconnected', room => {
// Detach the local media elements
room.localParticipant.tracks.forEach(publication => {
const attachedElements = publication.track.detach();
attachedElements.forEach(element => element.remove());
});
});
// To disconnect from a Room
room.disconnect();
}
I also tried to save "room" to a global variable when it's created and then passing that variable into the disconnect function. But even then I cannot call the room.on
.
I seem to be misunderstanding something basic in how to use the API to terminate a room.