Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to a global event triggered by WebCam Error: NotAllowedError

I'm using ar.js which uses the users webcam and issues a permission prompt to do so. What I want is to listen to a global event triggered by this dialogue if the user either allows or denies access to the webcam or has done so previously.

I've tried with global listeners like:

 document.documentElement.addEventListener("error", e=>{console.log("GOT ERROR : ", e)})
 window.addEventListener("error", e=>{console.log("GOT ERROR : ", e)});

WebRTC errors on MDN references only global error events.

like image 709
droid001 Avatar asked Nov 06 '22 21:11

droid001


1 Answers

I don't know ar.js events, and can't answer whether it has some direct way to observe this.

If you're asking for a way to hack around it, then there's no such global event in browsers. NotAllowedError is from calling await navigator.mediaDevices.getUserMedia().

But if you know approximately when it's prompting the user, then you can do a parallel request, like this:

// library
(async () => {
  video.srcObject = await navigator.mediaDevices.getUserMedia({video: true});
})();

// us
(async () => {
  try {
    await navigator.mediaDevices.getUserMedia({video: true});
    console.log("GOT CAM");
  } catch (e) {
    console.log("GOT ERROR : " + e);
  }
})();

This should give you the notification you want without causing a second user prompt.

It works because the spec mandates that getUserMedia must succeed without prompting the user again if the page already has a camera stream.

If you don't know when it'll prompt, then you'd need to override the getUserMedia method on the navigator.mediaDevices object. Various libraries like adapter.js do this successfully, if you need an example.

like image 54
jib Avatar answered Nov 14 '22 11:11

jib