Search code examples
javascriptwebrtcmicrophonemediadevices

Check if permissions exist on WebRTC navigator.mediaDevices


Desired goal:

User enters page. If access / permissions is already granted on navigator.mediaDevices enumerate devices and show a drop-down from where to choose.

If no permissions display a connect button which upon click does navigator.mediaDevices.getUserMedia, which displays the grant browser internal option. If granted enumerate devices.

I do not want to do the getUserMedia upon user entering the page as:

  1. There is other utilities that does not require User Media, only require audio, optionally audio/video etc.
  2. Find the built-in popup when entering a site asking for permission extremely obtrusive, ugly, distracting and so on.

I want the user to be presented by a short informative description before clicking "open" device(s) if needed.


Obstacle:

I can use enumerateDevices and check if device.label is empty or not. But not sure if this is reliable. It should always be empty when no access granted, but does devices always get a label when access is granted? Is this a reliable check?

Have searched around and read on MDN but can not find any API-point on this.

(Secondary I wonder if there is a way to revoke access from JavaScript. As in displaying a button that revokes granted access. (Guess I might have to ask that as a separate question.))


Edit: (Forgot to include.) As per w3 spec it say

https://www.w3.org/TR/webrtc/#dom-datachannel-label

label of type USVString, readonly

The label attribute represents a label that can be used to distinguish this RTCDataChannel object from other RTCDataChannel objects. Scripts are allowed to create multiple RTCDataChannel objects with the same label. On getting, the attribute MUST return the value of the [[DataChannelLabel]] slot.

But not sure if this is the correct place to look at it + as noted on MDN: https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo#instance_properties

Note: For security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. The set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user.

But again, not sure if label is always set when granted.


Solution

  • enumerateDevices and checking the device labels is a pretty good way to check if a persistent permission exists. The permissions API supports this as well https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query but may be less interoperable.

    Chrome is also testing a new way to achieve this, described in https://developer.chrome.com/blog/permission-element-origin-trial?hl=en