Help with adding this window.alert to the script

The web video recorder script (below) works successfully (but not in IE).
I found this code that is supposed to alert an IE user to “try Chrome”, added in to the web recorder script, and tried a test in IE11, but didn’t see the alert. Any help will be appreciated:

function init() {
    console.log('init');
    try {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    } catch (e) {
        window.alert('Your browser does not support WebVideo, try Google Chrome');
    }
    }

Here is the web video recorder script without the above window.alert function. Can you tell me if something needs to be changed with the alert?

And then suggest the ideal spot to place the alert in the script below, please?

<script>
        var video = document.querySelector('video');
        var recorded_video = video;
        var recorder; // globally accessible
        var global_camera;


        function captureCamera(callback) {
            navigator.mediaDevices.getUserMedia({
                audio: true,
                video: true
            }).then(function (camera) {
                callback(camera);
            }).catch(function (error) {
                alert('Unable to capture your camera. Please check console logs.');
                console.error(error);

            });
        }



        function startCamera() {
            //document.getElementById('btn-start-camera').disabled = true;
            document.getElementById('btn-start-recording').disabled = false;
            //document.getElementById('btn-stop-camera').disabled = false;
            captureCamera(function (camera) {
                setSrcObject(camera, video);
                video.play();
                global_camera = camera;
                video.controls = false;
            });
        }

        function startRecording() {
            recorder = RecordRTC(global_camera, {
                type: 'video'
            });
            recorder.camera = global_camera;
            document.getElementById('btn-start-recording').disabled = true;
            document.getElementById('btn-stop-recording').disabled = false;
  		    video.controls = true;
            recorder.startRecording();
        }

        function stopRecording() {
            document.getElementById('btn-stop-recording').disabled = true;
            document.getElementById('upload-video').disabled = false;
            document.getElementById('btn-start-recording').disabled = false;
            video.controls = true;
            recorder.stopRecording(stopRecordingCallback);
        }

        function stopCamera() {
            if (recorder)
                stopRecording();
            // release camera
            global_camera.getTracks().forEach(function (track) {
                track.stop();
            });

            global_camera.stop();
        }

        function stopRecordingCallback() {
            recorded_video.src = URL.createObjectURL(recorder.getBlob());
            PrepareBlob();
            document.getElementById("upload-video").disabled = false;
            recorder.destroy();
            recorder = null;
            stopCamera();
        }
        var blob, fileName, fileObject;

        function PrepareBlob() {
            // get recorded blob
            blob = recorder.getBlob();
            // generating a random file name
            fileName = getFileName('webm');
            // we need to upload "File" --- not "Blob"
            fileObject = new File([blob], fileName, {
                type: 'video/webm'
            });
        }

        function InitUploading() {
            uploadToPHPServer(fileObject, function (response, fileDownloadURL) {
                if (response !== 'ended') {
                    document.getElementById('header').innerHTML = response; // upload progress
                    return;
                }
                document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL +
                    '" target="_blank">' +
                    fileDownloadURL + '</a>';
                alert('Successfully uploaded recorded blob.');
                // preview uploaded file
                video.src = fileDownloadURL;
                // open uploaded file in a new tab
                window.open(fileDownloadURL);
            });
        }

        function uploadToPHPServer(blob, callback) {
            // create FormData
            var formData = new FormData();
            formData.append('video-filename', blob.name);
            formData.append('video-blob', blob);
            callback('Uploading recorded-file to server.');
            makeXMLHttpRequest('save.php', formData, function (progress) {
                if (progress !== 'upload-ended') {
                    callback(progress);
                    return;
                }
                var initialURL = 'uploads/' + blob.name;
                callback('ended', initialURL);
            });
        }

        function makeXMLHttpRequest(url, data, callback) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    if (request.responseText === 'success') {
                        callback('Upload Complete');
                        return;
                    }
                    alert(request.responseText);
                    window.location.href = '/index.com/';
                    return;
                }
            };
            request.upload.onloadstart = function () {
                callback('Upload started...');
            };
            request.upload.onprogress = function (event) {
                callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
            };
            request.upload.onload = function () {
                callback('Progress Ending');
            };
            request.upload.onload = function () {
                callback('Upload Complete');
            };
            request.upload.onerror = function (error) {
                callback('Upload Failed.');
            };
            request.upload.onabort = function (error) {
                callback('Upload aborted.');
            };
            request.open('POST', url);
            request.send(data);
        }
        // this function is used to generate random file name
        function getFileName(fileExtension) {
            var d = new Date();
            var year = d.getUTCFullYear();
            var month = d.getUTCMonth();
            var date = d.getUTCDate();
            return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
        }

        function getRandomString() {
            if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                var a = window.crypto.getRandomValues(new Uint32Array(3)),
                    token = '';
                for (var i = 0, l = a.length; i < l; i++) {
                    token += a[i].toString(36);
                }
                return token;
            } else {
                return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
            }
        }
        startCamera();
    </script>

If you’re just testing for getUserMedia support, then you can just test that navigator.getUserMedia exists.

if (!navigator || !navigator.getUserMedia) {
    // doesn't support getUserMedia
}

You can add support for getUserMedia if you like too, by using Modernizr, which helps you to fill in support for any missing features.

Thanks for that reply and code.

Can you please help me a little more with how to add it into my existing script?

Sure, update the startCamera() section at the end of the code with:

if (!navigator || !navigator.getUserMedia) {
    window.alert('Your browser does not support WebVideo, try Google Chrome');
} else {
    startCamera();
}

Greatly appreciated - thanks

This activates in IE, but not FF. Any ideas?

It’s marked as deprecated
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia

This is a legacy method. Please use the newer navigator.mediaDevices.getUserMedia() instead. While technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise returning version

1 Like

Thanks for those replies.

I added “the newer navigator.mediaDevices.getUserMedia()”
and then wanted to give the alerted person a re-direct, so I changed window.alert to window.confirm, which works successfully, however, whether OK or Cancel is selected,
the person is re-directed. How can I make it so when the Cancel choice is selected, then the alerted User doesn’t get re-directed?

Here’s my current code:

		    if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
		           (window.confirm('Your browser does not support WebVideo, try Google/Chrome'))
		    	   {
		    window.location.href='https://../index.php';
		    };
		    		} else {
		    		    startCamera();
}

You forgot the “if”

Maintaining good indentation is vital to spotting problems, allowing you to fix them.

Here is your code, with the indentation fixed, but leaving the problems in there.

if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
    (window.confirm('Your browser does not support WebVideo, try Google/Chrome')) {
        window.location.href='https://../index.php';
    };
} else {
    startCamera();

You should be able to see that a second if keyword is required, and that the a closing curly brace is missing.

The semicolon after the curly brace shouldn’t be there either.

Thanks for enlightening me. This seems to work. Is it correct?

		    if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
		           if (window.confirm('Your browser does not support WebVideo, try Google/Chrome'))
		    	   {
		    window.location.href='https://../index.php';
		    };
		    		} else {
		    		    startCamera();
};

You missed the “grammar” fix

Some JavaScript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (ASI):

  1. A semicolon is inserted before, when a Line terminator or “}” is encountered that is not allowed by the grammar.
  1. A semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a complete program.
  1. A semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. These statements with “no LineTerminator here” rules are:

In case that’s confusing (and it is), basically my crude “rule” is that even if JavaScript can magically insert semicolons, I don’t rely on it but add a semicolon after every statement out of habit. (and perhaps a touch of OCD)

However, block curly braces group statements, they are not statements.

1 Like

There should be no semicolons at the end of the curly braces…

Much thanks again

The web cam recorder sciot I’m working with has the "navigator’, etc. code and the end of the script as shown below.

I tried to add this code (without success), so people trying to use the webcam recorder in IE will see an alert dialog box:

			if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
    (window.confirm('Your browser does not support WebVideo, try Google/Chrome')) {
        window.location.href='https://../index.php';
    };

But it won’t work with the code below. Any suggestions will be welcomed.

        <script>
            const video = document.querySelector('video')
            const startvideo = document.querySelector('.start')
            const stopvideo = document.querySelector('.stop')
            const upload = document.querySelector('.upload')
            const initRecorder = stream => {
            const recorder = new MediaRecorder(stream)
            let blob
              video.srcObject = stream
              startvideo.removeAttribute('disabled')
              video.addEventListener('loadedmetadata', () => {
              video.play()
              })
              recorder.addEventListener('dataavailable', ({ data }) => {
              video.srcObject = null
              video.src = URL.createObjectURL(data)
              // Create a blob from the data for upload
              blob = new Blob([data], { type: 'video/webm' })
              })

              startvideo.addEventListener('click', () => {
              stopvideo.removeAttribute('disabled')
              show()
              reset()
              start()
              recorder.start()

etc., etc, ............................

              navigator
                .mediaDevices
                .getUserMedia({ video: true })
                .then(initRecorder)
                .catch(console.error)

         </script>

So, I’ve tried this, with some corrections, yet the window.confirm message still doesn’t display in IE
Any suggestions/enlightenment will be appreciated.

............. etc. ....................................
		    if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
		           if (window.confirm('Your browser does not support WebVideo, try Google/Chrome'))
		    	   {
		    window.location.href='https://../index.php';
		    		} else {
		    		    startCamera();
}
}

              navigator
                .mediaDevices
                .getUserMedia({audio: true, video: true })
                .then(initRecorder)
                .catch(console.error)

         </script>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.