简体   繁体   中英

How to check with JavaScript that webcam is being used in Chrome

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM