Access Microphone from a Browser - JavaScript

How to trigger microphone permission popup on chrome (javascript)

You need to get the permission using the navigator object.

navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
console.log('You let me use your mic!')
})
.catch(function(err) {
console.log('No mic for you!')
});

Also you need to run it on HTTPS and on a website instead of using IP addresses

Chrome does not prompt user for camera and/or microphone access even in secure context

It turns out, having video with autoplay attribute in HTML or similar lines on page load in Javascript prevent Chrome from showing the prompt.

HTML that causes this problem:

<video autoplay="true"></video>

Javascript that causes this problem:

localVideo = document.createElement('video');
videoContainer.append(localVideo);
localVideo.setAttribute('id','localVideo');
localVideo.play();

My guess is that the issue has to do with Chrome autoplay policy. Perhaps, Chrome treats my website as providing bad user experience and blocks the prompt?

I removed <video> from HTML and altered Javascript to create a relevant DOM on getUserMedia:

let localStream = new MediaStream();
let localAudioTrack;
let localVideoTrack;
let localVideo;

const userMediaConstraints = {
video: true,
audio: true
};

navigator.mediaDevices.getUserMedia(userMediaConstraints)
.then(stream => {
localAudioTrack = stream.getAudioTracks()[0];
localAudioTrack.enabled = true;
localStream.addTrack(localAudioTrack);

localVideoTrack = stream.getVideoTracks()[0];
localVideoTrack.enabled = true;
localStream.addTrack(localVideoTrack);

localVideo = document.createElement('video');
videoContainer.append(localVideo);
localVideo.setAttribute('id','localVideo');
localVideo.srcObject = localStream;
localVideo.muted = true;

localVideo.play();
});

And now I get the prompt.

Can I reset media permissions with JavaScript?

No, the browser's security model for microphone and camera access are outside of JavaScript. All JavaScript can do is request access to these resources, what happens afterward is left for the browser manufactures to implement to protect their users.



Related Topics



Leave a reply



Submit