Select the camera while using navigate.getUserMedia()

You can use facingMode to choose "user" or "environment" for front or back camera respectively. Not sure about browser support but it works on Android Chrome 58.

Use

navigator.getUserMedia({video: { facingMode: { exact: "environment" } } },
successCallback, errorCallback);

or, to allow fallback to some other camera

navigator.getUserMedia({video: { facingMode: "environment" } },
successCallback, errorCallback);

instead of

navigator.getUserMedia({video: true}, successCallback, errorCallback);

From https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia


This example on simpl.info demonstrates the use of MediaStreamTrack.getSources to select from multiple video sources.

https://simpl.info/getusermedia/sources/

I can confirm that this works in Chrome 32.


//----------------------------------------------------------------------
//  Here we list all media devices, in order to choose between
//  the front and the back camera.
//      videoDevices[0] : Front Camera
//      videoDevices[1] : Back Camera
//  I used an array to save the devices ID 
//  which i get using devices.forEach()
//  Then set the video resolution.
//----------------------------------------------------------------------
navigator.mediaDevices.enumerateDevices()
.then(devices => {
    var videoDevices = [0,0];
    var videoDeviceIndex = 0;
    devices.forEach(function(device) {
    console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
    if (device.kind == "videoinput") {  
        videoDevices[videoDeviceIndex++] =  device.deviceId;    
    }
    });


    var constraints =  {width: { min: 1024, ideal: 1280, max: 1920 },
    height: { min: 776, ideal: 720, max: 1080 },
    deviceId: { exact: videoDevices[1]  } 
};
return navigator.mediaDevices.getUserMedia({ video: constraints });

})
.then(stream => {
    if (window.webkitURL) {
    video.src = window.webkitURL.createObjectURL(stream);
    localMediaStream = stream;
    } else if (video.mozSrcObject !== undefined) {
    video.mozSrcObject = stream;
    } else if (video.srcObject !== undefined) {
    video.srcObject = stream;
    } else {
    video.src = stream;
    }})
.catch(e => console.error(e));