skip to Main Content

I am trying to get access to webcam and display video stream for capturing photo. I am not even getting consent for camera access i.e. popup message .I searched a lot but couldn’t find anything.
Below is the code for it:

document.addEventListener("DOMContentLoaded", function() {
            console.log("DOM fully loaded and parsed");

            navigator.permissions.query({ name: 'camera' }).then(function(permission) {
                if (permission.state === 'denied') {
                    alert("Camera access is denied. Please allow camera access and reload the page.");
                }
            });

            const video = document.getElementById('video');
            if (!video) {
                console.error("Video element not found");
                return;
            } else {
                console.log("Video element found");
            }

            const canvas = document.getElementById('canvas');
            if (!canvas) {
                console.error("Canvas element not found");
                return;
            } else {
                console.log("Canvas element found");
            }

            const captureButton = document.getElementById('capture');
            if (!captureButton) {
                console.error("Capture button not found");
                return;
            } else {
                console.log("Capture button found");
            }

            const photoData = document.getElementById('photo_data');
            if (!photoData) {
                console.error("Photo data input not found");
                return;
            } else {
                console.log("Photo data input found");
            }
            
    // Get access to the camera
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
            console.log("Camera stream obtained");
            video.srcObject = stream;
            video.play();
        }).catch(function(error) {
            console.log("Error accessing camera: " + error);
            alert("Could not access the camera. Please check permissions.");
        });
    } else {
        alert("getUserMedia is not supported by your browser.");
    }

    // Capture photo
    captureButton.addEventListener("click", function() {
        const context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, 320, 240);
        const dataURL = canvas.toDataURL('image/png');
        photoData.value = dataURL;
        canvas.style.display = 'block';
    });
});

function submitForm() {
    const photoData = document.getElementById('photo_data').value;
    if (!photoData) {
        alert("Please capture a photo before submitting the form.");
        return false;
    }
    return true; // Ensures the form is submitted
}

i tried a lot and searched different articles but couldn’t find anything.Kindly guide me.

2

Answers


  1. The navigator.permissions.query({ name: 'camera' }) is not universally supported in all browsers. Relying on this might not be effective. Instead, use a more straightforward check with navigator.mediaDevices.getUserMedia() directly.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Webcam Capture</title>
    </head>
    <body>
        <video id="video" autoplay playsinline width="320" height="240"></video>
        <button id="capture">Capture Photo</button>
        <canvas id="canvas" width="320" height="240" style="display: none;"></canvas>
        <input type="hidden" id="photo_data">
        <button onclick="submitForm()">Submit</button>
    
        <script>
            document.addEventListener("DOMContentLoaded", async function () {
                const video = document.getElementById('video');
                const canvas = document.getElementById('canvas');
                const captureButton = document.getElementById('capture');
                const photoData = document.getElementById('photo_data');
    
                // Request access to the camera
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                    video.srcObject = stream;
                    console.log("Camera stream obtained");
                } catch (error) {
                    console.error("Error accessing camera: ", error);
                    alert("Could not access the camera. Please check permissions or use HTTPS.");
                    return;
                }
    
                // Capture photo
                captureButton.addEventListener("click", () => {
                    const context = canvas.getContext('2d');
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);
                    const dataURL = canvas.toDataURL('image/png');
                    photoData.value = dataURL;
                    canvas.style.display = 'block';
                    alert("Photo captured!");
                });
            });
    
            function submitForm() {
                const photoData = document.getElementById('photo_data').value;
                if (!photoData) {
                    alert("Please capture a photo before submitting the form.");
                    return false;
                }
                alert("Form submitted successfully with captured photo.");
                return true;
            }
        </script>
    </body>
    </html>
    
    
    Login or Signup to reply.
  2. The navigator.permissions.query method doesn’t prompt for permission; it only checks if permission has already been granted or denied. This means that the browser won’t show a camera access prompt based on this query alone. The getUserMedia API should handle this prompt when it’s called.

    Check the below code.

    document.addEventListener("DOMContentLoaded", function() {
        console.log("DOM fully loaded and parsed");
    
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const captureButton = document.getElementById('capture');
        const photoData = document.getElementById('photo_data');
    
        if (!video || !canvas || !captureButton || !photoData) {
            console.error("Required elements are missing.");
            return;
        }
    
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(function(stream) {
                    console.log("Camera stream obtained");
                    video.srcObject = stream;
                    video.play();
                })
                .catch(function(error) {
                    console.error("Error accessing camera:", error);
                    alert("Could not access the camera. Please check permissions and ensure you're using HTTPS.");
                });
        } else {
            alert("getUserMedia is not supported by your browser.");
        }
    
        
        captureButton.addEventListener("click", function() {
            const context = canvas.getContext('2d');
            context.drawImage(video, 0, 0, 320, 240); // Adjust dimensions as needed
            const dataURL = canvas.toDataURL('image/png');
            photoData.value = dataURL;
            canvas.style.display = 'block';
        });
    });
    
    function submitForm() {
        const photoData = document.getElementById('photo_data').value;
        if (!photoData) {
            alert("Please capture a photo before submitting the form.");
            return false;
        }
        return true;
    }
    

    Also, some browsers only allow access to the camera via secure origins (HTTPS). If you’re testing locally, try running it on a localhost server or deploying the code to an HTTPS server.
    And their could be previous saved browser settings to deny the access to the camera. Please check on it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search