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.

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.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks