I am trying to open a camera on a browser with javascript i have this code and it was working yesteday but when i tried today to open through mobile its saying NotAllowedError: The request is not allowed by the user agent or the platform in the current context.

<button id="but" class="btn btn-success" onclick="myFunction()" autoplay>
    OPEN WEB CAM
</button>

<br>
<div id="myDIV" style="display: none">
    <div class="video-container1">
        <video id="vid"></video>
        <i class="watermark2">TAKE A SCREENSHOT WITH THE BUTTON</i>
        <a class="watermark3" style="text-decoration: none;" href="og.php?u=/cl/i/g6v612">TAKE SCREENSHOT 
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="20px"><path d="M512 80c0 18-14.3 34.6-38.4 48c-29.1 16.1-72.5 27.5-122.3 30.9c-3.7-1.8-7.4-3.5-11.3-5C300.6 137.4 248.2 128 192 128c-8.3 0-16.4 .2-24.5 .6l-1.1-.6C142.3 114.6 128 98 128 80c0-44.2 86-80 192-80S512 35.8 512 80zM160.7 161.1c10.2-.7 20.7-1.1 31.3-1.1c62.2 0 117.4 12.3 152.5 31.4C369.3 204.9 384 221.7 384 240c0 4-.7 7.9-2.1 11.7c-4.6 13.2-17 25.3-35 35.5c0 0 0 0 0 0c-.1 .1-.3 .1-.4 .2l0 0 0 0c-.3 .2-.6 .3-.9 .5c-35 19.4-90.8 32-153.6 32c-59.6 0-112.9-11.3-148.2-29.1c-1.9-.9-3.7-1.9-5.5-2.9C14.3 274.6 0 258 0 240c0-34.8 53.4-64.5 128-75.4c10.5-1.5 21.4-2.7 32.7-3.5zM416 240c0-21.9-10.6-39.9-24.1-53.4c28.3-4.4 54.2-11.4 76.2-20.5c16.3-6.8 31.5-15.2 43.9-25.5V176c0 19.3-16.5 37.1-43.8 50.9c-14.6 7.4-32.4 13.7-52.4 18.5c.1-1.8 .2-3.5 .2-5.3zm-32 96c0 18-14.3 34.6-38.4 48c-1.8 1-3.6 1.9-5.5 2.9C304.9 404.7 251.6 416 192 416c-62.8 0-118.6-12.6-153.6-32C14.3 370.6 0 354 0 336V300.6c12.5 10.3 27.6 18.7 43.9 25.5C83.4 342.6 135.8 352 192 352s108.6-9.4 148.1-25.9c7.8-3.2 15.3-6.9 22.4-10.9c6.1-3.4 11.8-7.2 17.2-11.2c1.5-1.1 2.9-2.3 4.3-3.4V304v5.7V336zm32 0V304 278.1c19-4.2 36.5-9.5 52.1-16c16.3-6.8 31.5-15.2 43.9-25.5V272c0 10.5-5 21-14.9 30.9c-16.3 16.3-45 29.7-81.3 38.4c.1-1.7 .2-3.5 .2-5.3zM192 448c56.2 0 108.6-9.4 148.1-25.9c16.3-6.8 31.5-15.2 43.9-25.5V432c0 44.2-86 80-192 80S0 476.2 0 432V396.6c12.5 10.3 27.6 18.7 43.9 25.5C83.4 438.6 135.8 448 192 448z"/></svg>
        </a>
    </div>
</div>

This is the JavaScript code

<script>

    document.addEventListener("DOMContentLoaded", () => {
    var but = document.getElementById("but");
    var video = document.getElementById("vid");
    var mediaDevices = navigator.mediaDevices;
    vid.muted = true;
    but.addEventListener("click", () => {

        // Accessing the user camera and video.
        mediaDevices
        .getUserMedia({
        video: true,
        audio: true,
    })
    .then((stream) => {

        // Changing the source of video to current stream.
        video.srcObject = stream;
        video.addEventListener("loadedmetadata", () => {
        video.play();
    });
    })
    .catch(alert);
    });
    });
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
</script>

It looks like you are using the getUserMedia() method to access the user's camera and microphone on a web page. This method is used to programmatically access the user's media devices, such as the camera and microphone, from a web page.

However, in order for this method to work, the user must grant permission for the page to access their media devices. If the user has not granted permission, or if they have previously denied permission, then getUserMedia() will throw a NotAllowedError indicating that the request is not allowed.

To request permission to access the user's media devices, you can use the navigator.permissions.query() method to check the current permission state, and then use the Permission.request() method to prompt the user for permission if necessary.

Here is an example of how you can use these methods to request permission to access the user's camera and microphone:

// Query the current permission state for camera and microphone access.
navigator.permissions.query({ name: "camera" }).then((result) => {
  if (result.state == "granted") {
    // If the user has already granted permission, start the video stream.
    startVideoStream();
  } else if (result.state == "prompt") {
    // If the user has not granted permission, prompt them for permission.
    navigator.permissions.request({ name: "camera" }).then((result) => {
      if (result == "granted") {
        // If the user grants permission, start the video stream.
        startVideoStream();
      } else {
        // If the user denies permission, show an error message.
        alert("Permission to access the camera and microphone was denied.");
      }
    });
  } else {
    // If the user has previously denied permission, show an error message.
    alert("Permission to access the camera and microphone has been denied.");
  }
});

You can then use the startVideoStream() function to start the video stream using the getUserMedia() method, as in your original code.

It's important to note that the navigator.permissions API is not supported by all browsers, so you may need to provide an alternative implementation for browsers that do not support this API. You can check the compatibility of this API on caniuse.com.

I dont have function startVideoStream(); and i have found this code from this website Could you mind do the script for me so i can learn from the example?

I am pretty much noob at JAVASCRIPT but i like it to see how it would look on a phone and experiment with it. THANK YOU so much for your answers!

And BTW my code on desktop/laptop browsers work

I would really like to play with this camera feature because its fun.

Are you still here? @
Skillz_1

From the web: "Recent versions of browsers have stopped exposing the camera API when HTTPS is not used."
And the error you reported can be the result. I can't know if your site is HTTPS or not but maybe your code is fine and the problem is elsewhere such as this or the user declined permissions to the browser.

I didn't quite understand, what exactly do you need?

commented: i want to open the front camera sucessfully +0

Yes my website is prottected with https with CloudFlare

I just want to open the camera through browsers on mobile and desktop successfully :)

As i remember i clicked "Deny" on the permissions when visited through mobile yesterday, i visited through 3 different mobile devices and the webcam was starting correctly. And That was it.
Magically don't work anymore only on mobile devices.

It comes Error on chrome (Permission Denied.)
Firefox (NotAllowedError: The request is not allowed by the user agent or the platform in the current context.)
Safari (There is no error displayed. BUT still cannot open the user cam)

If you clicked Deny then I see nothing wrong with it giving up this error.

But, and this is a stretch, Chrome has a habit (feature) of syncing across machines. That is, you deny once, then other devices may shortly honor your choice in the matter.

Also, it would be incorrect behavior to allow access when the user clicked Deny.

Yes thats correct behavior but i restarted the devices and its still not working. And plus i have called my friend to check and he reported back the same
How do i solve this can you please help me?

commented: By not denying access. +16

Exploitable items like this get patched all the time. You claim it used to work so along with you clicking DENY I don't see why you would change your code now.

Find others to test this. I can't because I don't know the URL and I will NEVER sign up to a website to do a test for anyone. My choice, my rule. But if you have a clear easy URL to test with I don't mind.

In the meantime check those browser versions and see when they updated.

I think the solution is to manually check the permissions and if user grands them than to open the cam.

But so far i cannot make it. I hope someone with solution will come

The browsers are latest update on chrome and firefox. (My friend work in a mobile store he checked on 10 different devices)

So you are saying the server is playing a role because i have clicked deny on my device and now others are affected?

It's a longshot but I do see permissions and more seem to sync on Chrome from my phone to PC.
By server I don't mean your web server but Chrome's cloud sync. Remember that most log in on their Chrome and from there, Chrome syncs bookmarks and more.

Is the URL to let me test a secret?

I can share the url but its not appropiate for the forum... I just find out if i got to the locker icon at the top of the browsers and allow permissions for camera and mic it will start the video.
I have a question: Why browsers doesnt ask manually the user with a popup windows to give permissions all the time?

To me it shows this is not a code issue. Just how modern(?) browsers work now. In other words, nothing broke in your code.

What you might have to do is add instructions on your site, near that button about how to enable this if the button doesn't seem to work.

commented: I impletented the above code in my website not more than 24h ago +6

It is likely that you have not requested the user's permission to use their camera in the current context. You need to use the .requestPermissions() method to prompt the user for permission before trying to access their camera. Try adding the following code before your getUserMedia call:

mediaDevices.requestPermissions()
.then(() => {
    mediaDevices.getUserMedia({
    video: true,
    audio: true,
    })
    .then((stream) => {
        // Changing the source of video to current stream.
        video.srcObject = stream;
        video.addEventListener("loadedmetadata", () => {
        video.play();
    });
    })
    .catch(alert);
})
.catch(alert);

Did i make it correct like this? Tried but doesn't work

document.addEventListener("DOMContentLoaded", () => {
    var but = document.getElementById("but");
    var video = document.getElementById("vid");
    var mediaDevices = navigator.mediaDevices;
    vid.muted = true;
    but.addEventListener("click", () => {
        // Accessing the user camera and video.
        mediaDevices.requestPermissions().then(() => {

        mediaDevices.getUserMedia({
        video: true,
        audio: true,
    }).then((stream) => {
        // Changing the source of video to current stream.
        video.srcObject = stream;
        video.addEventListener("loadedmetadata", () => {
            video.play();
        });
    }).catch(alert);
    });
});
.catch(alert);

I am not sure where do i close the bracket

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.