Skip to content

Instantly share code, notes, and snippets.

@bradley
Created November 16, 2018 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradley/f17bcef01ac27e0abbc84792a410c0bf to your computer and use it in GitHub Desktop.
Save bradley/f17bcef01ac27e0abbc84792a410c0bf to your computer and use it in GitHub Desktop.
Detect User Media Devices and Permission
class UserMediaDetector {
// Returns info on all user media devices in successful promise resolve.
getDevices() {
return new Promise((resolve, reject) => {
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
reject(Error("UserMediaDetector getDevices failed: enumerateDevices is not supported"));
return;
}
navigator.mediaDevices.enumerateDevices()
.then(devices => {
resolve(devices.map(
({ deviceId, groupId, kind, label }) => ({ deviceId, groupId, kind, label })
));
})
.catch(reject);
});
};
// Returns permitted status of given user media kind in successful promise resolve.
permitted(kind) {
return new Promise((resolve, reject) => {
if (!kind || !Object.values(UserMediaDetector.Kinds).includes(kind)) {
reject(Error(`UserMediaDetector permitted failed: kind ${kind} is not supported`));
return;
}
this.getDevices()
.then(devices => {
// Note: The presence of a `label` on a device indicates that it
// the device is active or persistent permissions are granted.
const permitted = !!devices.find(
device => device.kind === kind && !!device.label
);
resolve(permitted);
})
.catch(reject);
});
};
// Returns boolean value designating if all given media kinds are permitted in successful promise resolve.
permittedAll(kinds = Object.values(UserMediaDetector.Kinds)) {
return new Promise((resolve, reject) => {
const kindsArray = Array.isArray(kinds) ? kinds : Array.of(kinds);
const promises = kindsArray.map(kind => this.permitted(kind));
Promise.all(promises)
.then(permissionStates =>
resolve(permissionStates.every(isPermitted => isPermitted))
)
.catch(reject);
});
};
}
UserMediaDetector.Kinds = {
VideoInput: "videoinput",
AudioInput: "audioinput",
AudioOutput: "audioinput"
};
export default UserMediaDetector;
@bradley
Copy link
Author

bradley commented Nov 16, 2018

Example usage:

const detector = new UserMediaDetector();
detector.permitted(UserMediaDetector.Kinds.VideoInput)
  .then(weHaveCameraPermission => {
     console.log(weHaveCameraPermission);
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment