Skip to content

Instantly share code, notes, and snippets.

@IEvangelist
Created March 9, 2023 14:00
Show Gist options
  • Save IEvangelist/025de0ecb45b377b40cb7f371bde38fc to your computer and use it in GitHub Desktop.
Save IEvangelist/025de0ecb45b377b40cb7f371bde38fc to your computer and use it in GitHub Desktop.
/*
Requests the navigator.mediaDevices for video input.
*/
export async function requestVideoDevices() {
try {
// Ask the first time to prime the underlying device list.
let devices = await navigator.mediaDevices.enumerateDevices();
if (devices &&
(devices.length === 0 || devices.every(d => d.deviceId === ""))) {
await navigator.mediaDevices.getUserMedia({
video: true
});
}
// Ask again, if the user allowed it the device list is now poplated.
// If not, the const returns an empty array.
devices = await navigator.mediaDevices.enumerateDevices();
if (devices && devices.length) {
const deviceResults = [];
devices.filter(device => device.kind === 'videoinput')
.forEach(device => {
const { deviceId, label } = device;
deviceResults.push({ deviceId, label });
});
return JSON.stringify(deviceResults);
}
} catch (error) {
console.log(error);
}
return JSON.stringify([]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment