getUserMedia() allow user to continue even if permission is denied

Viewed 24

My sample getUserMedia() asks for permission for the camera and microphone.

let constraints = { audio: true, video: true };

navigator.mediaDevices.getUserMedia(constraints).then(stream => {
    // Do stuff
}).catch(e => alert(`getUserMedia error ${e.name}`))

If the user doesn't accept the camera and/or microphone permission request I get an alert error as expected.

Is it possible to still ask for audio and video, but if the user refuses, then their devices won't be used but, would still allow the user to browse the site?

Thank you.

1 Answers

If you want your code to run in either cases, then you'll have to split up and re-arrange your code in a way so that you can run it.

If the user accepts the stream, then go with doStuffWithStream, if not then call doStuffWithoutStream.

If something needs to happen in both cases, then you could use the finally method to run code in both cases.

function doStuffWithStream(stream) {
  // Do stuff with stream.
}

function doStuffWithoutStream() {
  // Do stuff without stream.
}

function doStuffEitherWay() {
  // Do stuff in both cases.
}

let constraints = { audio: true, video: true };

navigator.mediaDevices.getUserMedia(constraints).then(stream => {
  doStuffWithStream(stream);
}).catch(e => {
  alert(`getUserMedia error ${e.name}`);
  doStuffWithoutStream();
}).finally(() => {
  doStuffEitherWay();
});

Related