pmiranda
pmiranda

Reputation: 8470

React (not native) ask camera permission

I have a web app that needs to acces to camera, but I want to ask camera permission manually, because if the web app detects automatically camera permission, it will do it "too late".

What I need is to ask for permission, then I could render a 3rd party javascript function that renders a camera.

With react native is easy, but with normal React I can't find a way to ask when I want those permissions, for Chrome and Safari.

Any idea?

Upvotes: 9

Views: 15080

Answers (2)

pmiranda
pmiranda

Reputation: 8470

Prior to the link on the comment of @Shubh (thanks) I get it working only for Chrome:

navigator.permissions.query({ name: 'camera' })
  .then((permissionObj) => {
    console.log(permissionObj.state);
    permission = permissionObj.state;
  })
  .catch((error) => {
    console.log('Got error :', error);
  });

But this is not supported for iphone IOS (Safari).

Now with getUserMedia() API I have this code semi-working:

let stream = null;
const constraints = {
  video: true
};

try {
  stream = await navigator.mediaDevices.getUserMedia(constraints);
  /* use the stream */
} catch (err) {
  /* handle the error */
}

My only problem here is the light on the camera (desktop) get stucked, I'm trying to find now how to "close" the getUserMedia, I just want to grant permissions, like the first way.

Edit: now for turn off the camera I did this:

const askCameraPermission =
  async (): Promise<MediaStream | null> => await navigator.mediaDevices.getUserMedia({ video: true });

let localstream: MediaStream | null;
askCameraPermission()
  .then(response => {
    localstream = response;
  })
  .then(() => {
    localstream?.getTracks().forEach(track => {
      track.stop();
    });
  })
  .catch(error => console.log(error));

Upvotes: 6

Sabesan
Sabesan

Reputation: 712

navigator.getUserMedia({audio:true,video:true}, function(stream) {
  stream.getTracks().forEach(x=>x.stop());
}, err=>console.log(err));

Take the stream, get the tracks and stop them to turn off the camera. Camera will still flash, but it will turn off.

Here is the demo: https://codesandbox.io/s/camera-app-86me8?file=/src/App.js

Upvotes: 0

Related Questions