Browser Permissions And Switching The Cameras

Browser is an important part of running the web application. But for all web applications, the important part is the browser’s permission. The browser asks for permission whenever we try to access the application which contains notifications, camera access, microphone, etc.

But have we ever tried to deny those permissions and run the application? Or we have asked the permission deliberately to set the permission for the application.

How browsers ask permission whenever we try to access the web application.

Let’s consider the application using a camera and microphone.

If you want the browser to ask permission

navigator.mediaDevices.getUserMedia()
   .then((stream)=>{
       stream.getTracks().forEach((track)=>{
        console.log(track);       
   });
})

returns MediaStream which contains media devices information such as deviceId, deviceName, enabled, etc.

console.log(track) prints all the devices connected and their permissions.

If you want to ask permission for only audio then:

let params = { audio: true};

For both audio and video:

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

To set the camera by default front or rear, we can set facingMode

let params = { audio: true, video: { facingMode: { exact: "environment" } } };

For Front camera view “facingMode”: “front”

navigator.mediaDevices.getUserMedia(params)
   .then((stream)=>{
       stream.getTracks().forEach((track)=>{
        console.log(track);       
   });
})

Get deviceId and set the device to change the camera view

enumerateDevices() is a function used to get device data.

navigator.mediaDevices.enumerateDevices() 

.then(function(devices) { devices.forEach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceId); }); })

 .catch(function(err) { console.log(err.name + ": " + err.message); });

deviceId can be used to switch cameras or any device which is connected to the system.

How to get state if permission is given manually

Navigators.permissions detect browser permission which is set manually by the user.

navigator.permissions.query({name:'camera'})
.then(function(result) { if (result.state === 'granted') { showMap(); } else if (result.state === 'prompt') { showButtonToEnableMap(); }

Result.state returns the value as “granted”,”prompt”,”denied”.

name param contains values such as ‘camera’,’geolocation’,’bluetooth’ , ‘microphone’, ‘notifications’ etc.

Let’s consider an example that shows how permissions can be handled.
Example :

let errorCallback = (error)=> {
   if ((error.name == 'NotAllowedError') || (error.name == 'PermissionDismissedError')) {
          return false;
   }
 };
 if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({video:true,audio:true})
       .then((success)=>{
         if(navigator.mediaDevices || navigator.getUserMedia){
           let navigator : Navigator;
           navigator.permissions.query({name: "camera"})
           .then(({state}) => {
             if(state == 'granted'){
                console.log(“permission granted!”);            

             }else if(state == 'denied'){
               console.log(“permission denied!”);                 
             }
           })
         }
    },errorCallback);
  }

In the above example, we are checking if getUserMedia function is applicable for the browser. After that, we are asking for permission for ‘camera’ and ‘microphone’ bypassing params {video: true, audio: true}.

After asking permission we are checking if permission is granted using the navigator.permissions.query we can do further execution.

Let’s consider an example of how to switch cameras

Html file

<div id="video"></div>
<button id="cameraButton" type"button">Switch Camera</button>

Typescript file

public videoTag = document.getElementById("video");
Public cameraBtn =  document.getElementById("cameraButton");

this.cameraBtn.addEventListener('click', event => {
 const constraints = {
   video: true,
   audio: false,

   facingMode : “environment”
 };
 navigator.mediaDevices.getUserMedia(constraints)
   .then(stream => {
     videoTag.srcObject = stream;
   })
   .catch(error => {
     console.error(error);
   });
});

In the above example, we will switch the camera by clicking the switch camera button. By default, we have given the rear camera view, on click we can change the camera.

constraints.facingMode = “user”;

navigator.mediaDevices.getUserMedia will return device information and we will assign that stream to the video object which will switch the camera easily.

I have used a camera as an example, but instead, you can set any property and use it to ask for permission for your web application.

Refer link for more information – Navigator

I hope you like this blog and surely help you to make use of permission for web applications.

We Keep Sharing Tips And Learnings On Growth And Technology. Join Our Popular Newsletter That Goes Out Once In 2 Weeks

Devashree

Full-stack Developer

Devashree is a Full-stack developer with around 2 years of experience. Her expertise is in the angular framework and has worked on angular 4+ versions. She has also worked on nodeJS and Ionic framework version 3.

Get in touch for a detailed discussion.

What’s on your mind? Tell us a little bit about yourself and your question, and we will be in touch with you within 12 hours

Free eBook on Telemedicine Platform Development: All About Telemedicine

Download Free eBook Now!