5

If webcam is being used in Chrome, there will be a red dot on the tab for that page. And if other pages try to access webcam will get black for video. My question is, is it able to check with JavaScript that webcam is being used? How?

By using navigator.getUserMedia, I tried following code:

navigator.getUserMedia = navigator.getUserMedia ||
    navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
    navigator.msGetUserMedia;

navigator.getUserMedia({ audio: true, video: true }, function (stream) {
    var mediaStreamTrack = stream.getVideoTracks()[0];
    if (typeof mediaStreamTrack != "undefined") {
        mediaStreamTrack.onended = function () {alert('Your webcam is busy!')}
    } else errorMessage('Permission denied!');
}, function (e) {alert("Error: " + e.name);});

Pasting the code into console when a page is streaming video, I got no response.

Any ideas? Thanks!

r ne
  • 621
  • 7
  • 19

1 Answers1

9

Try instead using the enabled and readyState properties of the MediaStreamTrack object. You can then use a JavaScript array function such as some() to iterate through the tracks and check if any have enabled set to true and && readyState equal to string 'live":

navigator.getUserMedia = (navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetUserMedia ||
  navigator.msGetUserMedia);

if (navigator.getUserMedia) {
  navigator.getUserMedia({
      audio: true,
      video: true
    },
    function(stream) {
      // returns true if any tracks have active state of true
      var result = stream.getVideoTracks().some(function(track) {
        return track.enabled && track.readyState === 'live';
      });

      if (result) {
        alert('Your webcam is busy!');
      } else {
        alert('Not busy');
      }
    },
    function(e) {
      alert("Error: " + e.name);
    });
}

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • 1
    Thanks! This answer works. Additional question: If I want to turn off the stream, I add one line in the function(track) { track.stop(); return...} but it does not turn off the stream. Why? – r ne Feb 13 '17 at 20:58
  • 2
    It seems like this should work. However, even when the camera isn't already in use, this still returns "Your webcam is busy!". – spfursich Jun 22 '17 at 21:01
  • Could there be anything on your machine that is using the webcam? Some kind of webcam drivers or active browser plugins that are keeping the webcam in an active state? – Alexander Staroselsky Jun 23 '17 at 00:15
  • @rne did you get the solution? I did the same but it is not releasing the camera resource. Let me know if you got it working. thanks – Jivan Oct 04 '22 at 07:05