stop the webcam streaming of getUserMedia without page refreshing

Saving a reference to the LocalMediaStream like asgoth suggests is correct, but for me in Chrome 47. localStream.stop(); gave me an error:

Uncaught TypeError: localStream.stop is not a function

I got it to work by calling:

localStream.getVideoTracks()[0].stop();

You need to stop the LocalMediaStream object by executing its stop() method. I had similar problems. What you need to do is:

Keep a reference to the LocalMediaStream in the onSuccess callback function of the getUserMedia() execution:

var localStream;

onUserMediaSuccess = function(stream) {
   // attach to a video element
   ...
   // keep a reference
   localStream = stream;
};

Stop the LocalMediaStream where needed:

localStream.stop(); 

More info in my own question (and answer).


This seems to be a buggy area in Chrome, and the behavior is constantly changing. This seems to work, only if you are connected via http (not https):

var myStream;
function successCallback( stream ) {
    ...
    myStream = stream; // used to close the stream later
}

function closeStream(){
   myStream.stop(); 
   myStream = null;
}

For some strange reason this doesn't work on SSL (https) (Checked on Chrome for Linux, Ver 27 Dev)


Addition to asgoth's answer

localStream.stop() is deprecated in Chrome 45, removed in Chrome 47

If u call .stop() from multiple places, you can use the following helper for the stop function to keep the logic at one place.

var localStream;

onUserMediaSuccess = function(stream) {

  // re-add the stop function
  if(!stream.stop && stream.getTracks) {
    stream.stop = function(){         
      this.getTracks().forEach(function (track) {
         track.stop();
      });
    };
  }

  // attach to a video element
  ...
  // keep a reference
  localStream = stream;
};