JS, navigator.mediaDevices.getUserMedia() not working



I’m trying to get video from client’s Webcam. I wrote the code, and no errors occurred. However, when I try to get video, nothing shows up (in Google Chrome) or just a single frame of the video is displayed (in Mozilla Firefox). I have tested it out before and it worked completely fine, but now, I don’t know why, it doesn’t work. I searched for it, and found nothing about it. Any help is really appreciated. Thanks

Here’s my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    html, body {
        height: 100%;
    }
    body {
        margin: 0;
    }
    video {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: -1;
    }
    </style>
</head>
<body>
    <button id="shareBtn">Share Video</button>

    <script>
    async function startCapture(displayMediaOptions) {
        let stream = null;

        try {
            stream = await navigator.mediaDevices.getUserMedia(displayMediaOptions);
            video = document.createElement("video");
            video.srcObject = stream;
            document.body.appendChild(video);
        } catch(err) {
            console.error(err);
        }
    }
    document.getElementById("shareBtn").addEventListener("click", () => {

        startCapture({ video:true });

    });
    </script>
</body>
</html>

Answer

Your code is working, but video is paused. Add 1 line to your code:

<script>
    async function startCapture(displayMediaOptions) {
        let stream = null;

        try {
            stream = await navigator.mediaDevices.getUserMedia(displayMediaOptions);
            video = document.createElement("video");
            video.srcObject = stream;
            video.setAttribute('autoplay', true); /* THIS */
            document.body.appendChild(video);
        } catch(err) {
            console.error(err);
        }
    }
    document.getElementById("shareBtn").addEventListener("click", () => {

        startCapture({ video:true });

    });
</script>


Source: stackoverflow