Search code examples
javascripthtmltypescripttwiliotwilio-video

twilio video code leaving video tag behind when I detach track


So Im a bit confused.

The way this works, is each person in my video call already has space in the ui when they join. When they turn on their video the code attaches their track to their respective div space on the ui.

Just for clarity here is the start video code. It is unrelated to this question, but good for context.

startvideo(){
    navigator.mediaDevices.getUserMedia({video: true}).then((stream)=>{
      createLocalVideoTrack({
        deviceId: stream.id
      }).then(localVideoTrack =>{
        return this.videoclient.localParticipant.publishTrack((localVideoTrack)).then(publication =>{
          this.localvideotrack = localVideoTrack;
          let div = document.getElementById( this.videoclient.localParticipant.sid + 'vid');
          div.appendChild(localVideoTrack.attach());
          this.removenovideohtml(this.videoclient.localParticipant.sid);
          this.mms.getDevicesOnComputer();
          this.devicessubscription = this.mms.receiveDevices()
            .subscribe(
              (req: any)=>{
                this.devicesoptions = req;
              }
            );
        });
      });
    });
  }

and here is the end video code, this is in context:

endvideo(){
    if(this.localvideotrack != null){
      let div = document.getElementById( this.videoclient.localParticipant.sid + 'vid');
      this.localvideotrack.detach(div);
      this.localvideotrack.stop();
      this.videoclient.localParticipant.unpublishTrack(this.localvideotrack);
      this.addremovevideohtml(this.videoclient.localParticipant.sid);
    }
  }

now look what happens when I start and stop the video three times

2 blank chat boxes when there should only be the video

and the html of the picture above

the html

I have tried to add code to then manually remove the video elements after detaching the track but I have had no success. Wondering if you guys can help me. Thank you.


Solution

  • Twilio developer evangelist here.

    The detach method actually returns the media element that the track was previously attached to, which allows you to then remove the media element from the page if you no longer need it.

    You don't need to pass div to detach either, the video track is aware of the element it is attached to. This means you don't need to do the getElementById lookup either.

    I'd recommend you update the endvideo function to the following:

    endvideo(){
        if(this.localvideotrack != null){
          const mediaElements = this.localvideotrack.detach();
          mediaElements.forEach(mediaElement => mediaElement.remove());
          this.localvideotrack.stop();
          this.videoclient.localParticipant.unpublishTrack(this.localvideotrack);
          this.addremovevideohtml(this.videoclient.localParticipant.sid);
        }
    }