droid001
droid001

Reputation: 173

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.

Upvotes: 5

Views: 589

Answers (1)

jib
jib

Reputation: 42490

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.

Upvotes: 1

Related Questions