16

I want to create a video chat application using HTML 5 elements and JavaScript, and I don't want to use Flash to access the user's webcams.

How can I accomplish this using only HTML and JavaScript?

Braiam
  • 1
  • 11
  • 47
  • 78
Tamer El-Nasser
  • 249
  • 1
  • 3
  • 6

2 Answers2

18

At the moment of writing this the best solution is WebRTC. It is supported in Chrome, Mozilla and Opera, but still unavaialble in Internet Explorer and Safari.

Minimalistic demo.

Index.html

<!DOCTYPE html>
<head>
</head>
<body>
    <video></video>
    <script src="webcam.js"></script>
</body>

webcam.js

(function () {
    navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia);

    navigator.getMedia(
        // constraints
        {video:true, audio:false},

        // success callback
        function (mediaStream) {
            var video = document.getElementsByTagName('video')[0];
            video.src = window.URL.createObjectURL(mediaStream);
            video.play();
        },   
        //handle error
        function (error) {
            console.log(error);
        })   
})();

Read more here or there

Pawel Miech
  • 7,742
  • 4
  • 36
  • 57
  • 1
    This particular code won't work on Chrome until the user has clicked something within the DOM. I added a button that invokes the function above and everything works perfectly. – taystack Jul 19 '18 at 16:29
  • @taystack Do you have a fiddle or something ? I am curious on how. – shifu Jul 27 '18 at 04:41
  • @shifu https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#new-behaviors will tell you all the things. – taystack Aug 22 '18 at 21:13
3

Despite the fact the provided example is great and inspired me, at the time of writing this answer, the Navigator.getUserMedia() function is obsolete. I've rewritten the provided example using the video tag's srcObejct and promise approach.

<!DOCTYPE html>
<head>
</head>
<body>
    <video id="video-cam"></video>
    <script>
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(mediaStream => {
            const video = document.getElementById('video-cam');
            video.srcObject = mediaStream;
            video.onloadedmetadata = (e) => {
                video.play();
            };
        })
        .catch(error => {
            alert('You have to enable the mike and the camera');
        });
    </script>
</body>
Martin Makarsky
  • 2,580
  • 1
  • 17
  • 28