admin管理员组

文章数量:1330389

Let's say I'm using the getUserMedia javascript api in a browser. The browser asks the user for permission to use the camera or the microphone.

How can I detect when the browser is asking for these permissions, so I can explain to the user why the app is asking for permission?

Let's say I'm using the getUserMedia javascript api in a browser. The browser asks the user for permission to use the camera or the microphone.

How can I detect when the browser is asking for these permissions, so I can explain to the user why the app is asking for permission?

Share Improve this question asked Nov 13, 2012 at 4:24 mgerringmgerring 531 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

As far as I know this isn't directly possible, however you should be able infer that the user is seeing a prompt.

Presumably, since you are writing the javascript, you decide when you're going to call getUserMedia(), so you can offer additional explanation as part of the process that leads up to this. A well designed page should explain what's going on well enough that the user knows what's happening before they're prompted to turn over control of their webcam.

That said, you can infer that a user is seeing the permission prompt when you've sent the request, but have not received either an error callback or a success callback. Given that, you could set a timer at the same time that you first prompt for permission that fires if there is no success or error returned for a few seconds, in which case you could reasonably assume that the user has been presented with the browser prompt but not yet responded.

Starting with Chrome 64 you can use the Permissions API to query whether or not camera and microphone permissions have been granted:

navigator.permissions.query({name:'camera'}).then(function(result) {
    alert(result.state);
    if (result.state === 'granted') {
        //permission has already been granted, no prompt is shown
    } else if (result.state === 'prompt') {
       //there's no peristent permission registered, will be showing the prompt
    } else if (result.state === 'denied') {
       //permission has been denied
    }
});

The above only works in Chrome atm.

I've written more on the topic @ Using the Permissions API to Detect How Often Users Allow or Deny Camera Access

This is a native UI feature and is not exposed to JavaScript, so it's not possible to detect when the dialog box appears. All browsers that support getUserMedia ask for permission, however, so if you detect for support of the getUserMedia API then you could show your explanation at that point and users on other browsers wouldn't see it.

本文标签: javascriptHow can I detect the browser asking a user for device permissionsStack Overflow