reprompt for permissions with getUserMedia() after initial denial

后端 未结 5 1020
我在风中等你
我在风中等你 2020-12-02 09:56

How do we go about requesting camera/microphone access with getUserMedia() after being denied once?

I\'m working with getUserMedia to access the user\'s camera and p

5条回答
  •  再見小時候
    2020-12-02 10:23

    Chrome implements the Permissions API in navigator.permissions, and that applies to both camera and microphone permissions too.

    So as of now, before calling getUserMedia(), you could use this API to query the permission state for your camera and microphone :

     navigator.permissions.query({name: 'microphone'})
     .then((permissionObj) => {
      console.log(permissionObj.state);
     })
     .catch((error) => {
      console.log('Got error :', error);
     })
    
     navigator.permissions.query({name: 'camera'})
     .then((permissionObj) => {
      console.log(permissionObj.state);
     })
     .catch((error) => {
      console.log('Got error :', error);
     })
    

    On success, permissionObj.state would return denied, granted or prompt.

    Useful SF question/answer here

    For a cross browser solution, one simple approach can be to monitor the time difference between when the getUserMedia() Promise is called, and when it is rejected or resolved, like so :

    // In the Promise handlers, if Date.now() - now < 500 then we can assume this is a persisted user setting
    var now = Date.now();
    navigator.mediaDevices.getUserMedia({audio: true, video: false})
    .then(function(stream) {
      console.log('Got stream, time diff :', Date.now() - now);
    })
    .catch(function(err) {
      console.log('GUM failed with error, time diff: ', Date.now() - now);
    });
    

    This Medium article gives more details.

    Hope this helps!

提交回复
热议问题