DEV Community

Cover image for JavaScript Navigator Media Devices πŸ“· πŸŽ™οΈ
alexpaper
alexpaper

Posted on

JavaScript Navigator Media Devices πŸ“· πŸŽ™οΈ

As you know, with Navigator.mediaDevices you can access to connected media input devices in your machine like cameras and microphones.

Taking advantage of the potential of this amazing API you can create pretty awesome web app in a few code lines.

For example you can create a simple app to
take a picture using the computer onboard camera.

The MediaDevices.getUserMedia() method prompts the user for permission to use a media input which produces a MediaStream with tracks containing the requested types of media.

It returns a Promise that resolves to a MediaStream object, using this async function you can attach the camera stream as source in your video web page

const video = document.querySelector('video');
// Navigator video stream
async function videoStream (){
    try{
        const stream = await navigator.mediaDevices.getUserMedia({
            video:true,
            audio:false
        });
        // Set video source
        video.srcObject = stream;
  }catch(err){
        console.log(err);
    }
}

Enter fullscreen mode Exit fullscreen mode

Some Privacy and security considerations

As an API that may involve significant privacy concerns, getUserMedia()'s specification lays out a wide array of privacy and security requirements that browsers are obligated to meet.

getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, navigator.mediaDevices is undefined, preventing access to getUserMedia().
A secure context is, in short, a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost.
In addition to that, user permission is always required to access the user's audio and video inputs.

This is a little youtube guide that show how simple it is implementig navigator API πŸ“Έ.

Top comments (0)