Sobes.tech
Middle

navigator.mediaDevices will be undefined — how to make it not undefined?

sobes.tech AI

Answer from AI

If navigator.mediaDevices is undefined, it usually means that the browser does not support the MediaDevices API or access to it is blocked.

To make navigator.mediaDevices available:

  1. Ensure you are using a modern browser that supports the MediaDevices API (latest versions of Chrome, Firefox, Edge, Safari).
  2. Run your site over HTTPS, as access to camera and microphone is only allowed on secure connections.
  3. Check that the page is not loaded from a local file (file://), but through HTTP(S).
  4. If needed, you can add a polyfill or use navigator.getUserMedia with prefixes for older browsers, but this is deprecated.

Example of checking and using:

if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => {
      // Use the video stream
    })
    .catch(error => {
      console.error('Error accessing camera:', error);
    });
} else {
  console.error('MediaDevices API is not supported');
}