loading...

Stopping a Webcam with JavaScript

morinoko profile image Felice Forby ・2 min read

I recently had to manually get a running web camera to turn off using JavaScript for a project at work.

I had a hard time figuring out JavaScript's MediaStream API so here are some quick notes on how I got the camera to stop.

If the camera is running through a video element, you can stop the video by getting its MediaStreamTrack object and using the stop() method:

const video = document.querySelector('video');

// A video's MediaStream object is available through its srcObject attribute
const mediaStream = video.srcObject;

// Through the MediaStream, you can get the MediaStreamTracks with getTracks():
const tracks = mediaStream.getTracks();

// Tracks are returned as an array, so if you know you only have one, you can stop it with: 
tracks[0].stop();

// Or stop all like so:
tracks.forEach(track => track.stop())

Another way to get all the MediaStreams is to use mediaDevices.getUserMedia() which is called on navigator tracks. It prompts the user for permission (if not already granted) to access the media devices. It will return a Promise so you can write the necessary code within the Promise's then:

navigator.mediaDevices.getUserMedia({video: true, audio: false})
  .then(mediaStream => {
    const stream = mediaStream;
    const tracks = stream.getTracks();

    tracks[0].stop;
  })

Make sure you only call getUserMedia once or stop() won't work, so if your code or a library you're using calls getUserMedia on the page to activate a camera, then you probably won't be able to use this method.

References

Posted on Aug 9 '19 by:

morinoko profile

Felice Forby

@morinoko

I'm a former Japanese translator turned full-stack web engineer. I work mostly with Ruby and Rails, and love working on both the back-end and the front-end. I'm based in Japan :)

Discussion

markdown guide