'How to detect user & environment camera availability

Is there a reliable way to detect if a front facing camera and environment facing camera exists across modern browsers?

I have seen something like getCapabilities to get the facingMode field, but that is not supported by firefox.

My current solution is this function which uses exact to determine if each camera is supported.

const isCameraSupported = async (facingMode) => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: {
          exact: facingMode,
        },
      },
      audio: true,
    });
    const tracks = stream.getTracks();
    tracks.forEach((track) => {
      track.stop();
    });
    return {
      status: 'known',
      available: true,
    };
  } catch (error) {
    if (error.name === 'OverconstrainedError' && error.constraint === 'facingMode') {
      return {
        status: 'known',
        available: false,
      };
    }
    return {
      status: 'unknown',
      available: false,
    };
  }
};

So I end up calling it like

const isUserSupported = await isCameraSupported('user');
const isEnvironmentSupported = await isCameraSupported('environment');

// start actual camera

Ultimately I end up starting 3 streams in total (2 which end immediately). Is there a better way to go about this? I want to make sure I'm not causing any issues starting and stopping streams so quickly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source