TL;DR
You can display your webcam's live video in the browser with just HTML and JavaScript, no plug-in required. A video element with autoplay and playsinline shows the stream, and navigator.mediaDevices.getUserMedia({ video: true }) asks for permission and, once granted, hands back a stream you assign to the video element's srcObject.
- Every modern browser only allows webcam access on pages served over HTTPS, though local testing on localhost still works.
- If permission is denied, there's no camera, or another app is using it, the catch block gets an error whose name says which.
- We can pass extra settings (known as constraints) like facingMode: "environment" and an ideal width and height to pick the back camera and the video size.
- Calling stop() on every track from getTracks() turns the webcam off; hiding the video element leaves it running.
Learn how the video element combined with the getUserMedia function can help you display your webcam's video stream in the browser. If you'd rather watch than read, this video walks through everything we'll build:
Accessing your webcam via your browser used to involve a...pardon the profanity, a plugin. That's right. To connect to a webcam and gain access to its video stream, you had to rely on something primarily created in Flash or Silverlight. While that approach certainly worked for browsers that supported plug-ins, it didn't help for the increasing number of browsers that aim to be plugin-free. This inability to natively access the webcam without relying on 3rd party components was certainly a gap in the HTML development story - especially on mobile devices. Thankfully, those plug-in days are long gone.
The W3C filled this gap with the Media Capture and Streams spec. This spec defines, among various other things, how to communicate with a webcam device using just a little bit of JavaScript. The good news is that every major browser supports it today, on desktops as well as on phones and tablets.
By the time you reach the bottom of this page, you will have learned how to take your webcam's video stream and display it using only some HTML and JavaScript.
Onwards!
The Example
Before proceeding further, let's first take a look at an example that is nearly identical to what you will be creating. Once you give your browser permission to use your webcam, you should see a live version of yourself (or whatever your webcam is pointing at) in the gray box below:
Try it
- Press Start webcam
- Choose Allow when your browser asks
- Press Stop webcam to turn it off
If you do not give your browser permission to access the webcam, you will not see anything interesting. You will just see a beautiful gray box with a finely crafted dark gray border, plus a note letting you know the webcam was blocked.
Webcams Need HTTPS
Every modern browser only lets a page use the webcam when that page is served over HTTPS, or what the spec calls a secure context. Chrome started this trend with a security change back in 2015, and the other browsers followed. On a plain http:// page, navigator.mediaDevices doesn't even exist!
You can still develop and test locally, because http://localhost and http://127.0.0.1 count as secure. Opening your HTML file straight from your desktop works in some browsers and not in others, so a tiny local server is the safer bet. There is one more detail to keep in mind. If your webcam code lives inside an iframe that comes from another site, that iframe also needs an allow="camera" attribute.
If you didn't see a permissions prompt, you may have just overlooked it or dismissed it. Different browsers do different things when they ask you for permission to use the webcam. For example, here is what Chrome's prompt looked like back when this article first came out. Today's prompt is a small bubble that drops down from the address bar, but it asks the same question:

If you denied permission accidentally (or intentionally), reloading the page may not bring the prompt back, because browsers remember your answer. Click the camera or site settings icon in your address bar, switch the camera back to Allow, and then reload this page to get a crack at acing this test again.
Note: Browser Support
Webcam access works in every modern browser, including Safari on the iPhone and iPad (since iOS 11) and Chrome on Android. If you need to support something older, check out caniuse's statistics. These days, the two things that trip people up the most are HTTPS and permissions, and we just looked at both of them.
How Does Webcam Access Work?
To help make the code we will be writing...easier to write, let's look at an overview of how everything works using plain old English. There are two components that do all the heavy lifting in getting data from your webcam displayed on your screen. They are the HTML video element and the JavaScript getUserMedia function:

The video element is pretty straightforward in what it does. It is responsible for taking the video stream from your webcam and actually displaying it on the screen.
The interesting piece is the getUserMedia function. This function allows you to do three things:
- Specify whether you want to get video data from the webcam, audio data from a microphone, or both.
- If the user grants permission to access the webcam, hand you a stream of webcam data that you can process further.
- If the user does not grant permission to access the webcam or your webcam runs into some other kind of error, let you know with an error so you can handle it.
For what we are trying to do, we call the getUserMedia function and tell it to only retrieve the video from the webcam. We'll leave the microphone out of this one! Once we retrieve the video stream, we send it to our video element for display on our screen.
If this sounds pretty straightforward, that's because it actually is pretty. Let's put all of this straightforward English-sounding description into HTML and JavaScript in the next section.
How Do We Display the Webcam Video?
In this section, let's go ahead and display our webcam data to the screen. First, let's add the HTML and CSS:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display Webcam Stream</title>
<style>
#container {
margin: 0px auto;
width: 500px;
height: 375px;
border: 10px #333 solid;
}
#videoElement {
width: 500px;
height: 375px;
background-color: #666;
}
</style>
</head>
<body>
<div id="container">
<video autoplay playsinline id="videoElement">
</video>
</div>
<script>
</script>
</body>
</html>
In a new document, go ahead and add all of the HTML and CSS that you see above. The important thing to note in this snippet is the video tag:
<video autoplay playsinline id="videoElement">
</video>
Our video tag has an id value of videoElement, and it has the autoplay attribute set. By setting the autoplay attribute, we ensure that our video starts to display automatically once we have our webcam video stream. The playsinline attribute is for iPhones. Without it, iOS may try to play our video full screen instead of keeping it inside our page.
If you preview what your page looks like in your browser, what you will see will look as follows:

Yes, this looks pretty plain and boring now. That is because we haven't added the JavaScript that ties together our video element with your webcam. We'll do that next!
Inside your script tag, add the following code:
const video = document.querySelector("#videoElement");
if (navigator.mediaDevices?.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
Once you've added this code, save your HTML document and preview your page. Provided your page is served over HTTPS (or from localhost), you should see your webcam video stream after you've given your browser permission to access it.
Examining the Code
Now that you have a working example, let's go through our code line-by-line to understand how the verbal overview you saw earlier matches the code that you just added.
Let's start at the very top:
const video = document.querySelector("#videoElement");
We first declare a variable called video, and it is initialized to our video element that lives in the HTML. We get our paws on the video element by using querySelector and specifying the id selector that targets it.
Next up is our code for accessing the getUserMedia API:
if (navigator.mediaDevices?.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
The getUserMedia method is supported by every modern browser, but it doesn't hurt to check first before starting to access properties on it. Remember, navigator.mediaDevices does not even exist on a page that is not served over HTTPS. That is why we check with ?. here. This little operator (known as optional chaining) lets us look for getUserMedia only if mediaDevices exists. If mediaDevices is missing, the whole expression just becomes undefined instead of throwing an error. This if statement ensures that our media-related code only runs if getUserMedia is actually available.
The rest of our code is responsible for accessing our webcam and streaming the visuals to the screen. Before we go through and look at that, let's take a step back and talk about how getUserMedia actually works. It takes one argument that specifies what are known as constraints. Constraints allow you to control, among various things, whether video is allowed, whether audio is allowed, how big to make the video dimensions, whether to prefer a front-facing camera over a back-facing one, the video frame rate, and more. You represent these constraints as just objects and properties. Nothing fancy there.
In our code, you can see constraints in action below:
if (navigator.mediaDevices?.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
All we are telling getUserMedia is to specify a constraints object whose video property is set to true. This means that default settings will be used in capturing the visuals and displaying them. This isn't the most exciting constraint to set, but it gets the job done. To see the full range of constraints you can specify, the MDN article on getUserMedia goes through all the fun details.
Beyond constraints, there is another very important detail we need to know about the getUserMedia method. What it returns is a promise that resolves to an object of type MediaStream. When the promise successfully resolves, you can access the underlying media stream and perform any additional actions.
In our code, we are keeping things simple and just setting our stream to our video element's srcObject property:
if (navigator.mediaDevices?.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
If there are any failures, the catch block will kick in. Inside our catch block, we log the error object we get. In the next section, we will see what useful information this error object carries.
What If Something Goes Wrong?
There are a handful of reasons our webcam might not show up. The person might say no to the permission prompt, or they might not have a webcam at all. It is also possible that another app (like a video call that is still running) is holding on to the webcam. To help us tell these cases apart, the error our catch block receives has a name property:
.catch(function (error) {
if (error.name === "NotAllowedError") {
console.log("Permission to use the webcam was denied.");
} else if (error.name === "NotFoundError") {
console.log("No webcam was found.");
} else if (error.name === "NotReadableError") {
console.log("The webcam is busy. Another app may be using it.");
} else {
console.log("Something went wrong!", error);
}
});
In a real app, instead of logging to the console, we would show a friendly message on the page. If you block the webcam in the example at the top of this page, you will see us do exactly that. A short message is a lot nicer than leaving someone staring at an empty gray box and wondering what happened.
Choosing the Front or Back Camera
Setting video to true gets us whatever camera the browser picks by default. On a phone, that is usually the front-facing selfie camera. To ask for a particular camera or video size, we pass an object to video instead:
navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment",
width: { ideal: 1280 },
height: { ideal: 720 }
}
})
The facingMode property is how we choose a camera. A value of user asks for the camera pointing at the person (the selfie camera), and environment asks for the camera pointing away from them (the back camera on a phone). On a laptop with just one webcam, the browser will happily give us that one webcam either way.
The ideal values for width and height say that we would like a 1280 by 720 video, but we will take the closest thing the camera can do. If we used exact instead and the camera could not deliver, getUserMedia would fail with an OverconstrainedError. This is why we usually go with ideal. We would rather get a video that is a little smaller (or bigger) than what we asked for than get no video at all.
If you want to let people pick from a list of every camera they have, navigator.mediaDevices.enumerateDevices() returns all of their cameras and microphones. Each camera has a deviceId that we can ask for with video: { deviceId: { exact: id } }. Just note that the camera names (the label property) stay empty until the person has given our page permission to use a camera.
Using Async and Await
Because getUserMedia returns a promise, we can also use async and await instead of then and catch. Here is the same code written that way, wrapped inside a function that runs when someone clicks a button:
const video = document.querySelector("#videoElement");
const startButton = document.querySelector("#startButton");
async function startWebcam() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
} catch (error) {
console.log("Something went wrong!", error);
}
}
startButton.addEventListener("click", startWebcam);
Both versions do exactly the same thing, so use whichever one reads better to you. What I would copy from this version is the button. When the permission prompt shows up right after someone clicks a Start webcam button, they know exactly why our page is asking. If the prompt appears the moment our page loads, it looks a lot more suspicious, and people are more likely to say no to it.
Turning the Webcam Off
When we are done with the webcam, we should turn it off. Removing the video element or hiding it is not enough, because the webcam (and its little light) stays on for as long as our stream is still running. To actually stop the webcam stream, we need some code that looks as follows:
function stopWebcam() {
const stream = video.srcObject;
stream.getTracks().forEach(function (track) {
track.stop();
});
video.srcObject = null;
}
Our stream (a MediaStream) is made up of one or more pieces, one for the video and another for the audio if we asked for it. These pieces are known as tracks. We get all of the tracks by calling getTracks, and we release the webcam by calling stop on each one. Once that is done, we set srcObject to null to clear our video element and bring our gray box back. If we hook stopWebcam up to a Stop webcam button, we have the full example from the top of this page. This thread goes into more detail on stopping the stream along with a working example.
Frequently Asked Questions
How Do You Access Your Webcam in the Browser?
With just a little HTML and JavaScript, and no plug-in required. We add a video element with autoplay and playsinline set, then call navigator.mediaDevices.getUserMedia({ video: true }). Once the user grants permission, it hands back a stream that we assign to the video element’s srcObject, and our webcam’s live video shows up on the page.
What Does getUserMedia Do?
getUserMedia lets us specify whether we want video from the webcam, audio from a microphone, or both. It takes a constraints object and returns a promise that resolves to a MediaStream once the user grants permission. If permission is denied or something else goes wrong, the catch block kicks in.
How Do You Give a Web Page Permission to Use Your Camera?
The browser shows a permission prompt when the page asks for the webcam, and different browsers display it differently. If you deny permission, accidentally or intentionally, you’ll just see an empty gray box. Browsers remember that answer, so use the camera or site settings icon in the address bar to switch the camera back to Allow, then reload the page.
Why Doesn’t My Webcam Work on a Web Page?
Every modern browser only allows webcam access on pages served over HTTPS, and on a plain http page navigator.mediaDevices doesn’t even exist. Testing locally on localhost or 127.0.0.1 still works. If the page is secure, check whether the camera was blocked earlier or whether another app is already using it.
How Do You Use the Back Camera on a Phone?
Pass a constraints object whose video property sets facingMode to environment, like getUserMedia({ video: { facingMode: "environment" } }). A value of user asks for the selfie camera instead. The same object can ask for an ideal width and height, and on a laptop with just one webcam, you get that webcam either way.
How Do You Stop the Webcam Stream?
Grab the stream from the video element’s srcObject, get its tracks with getTracks(), and call stop() on each one. That releases the webcam and turns off its light. Then set the video element’s srcObject to null to clear the video element.
Conclusion
So, there you have it - a look at how you can access a user's webcam video stream and display it in the browser. Once you get the video displayed, you can then do all sorts of things that you can do to videos in general. You can apply crazy filters with CSS, you can take a snapshot by drawing the video onto a canvas and saving that image, and you can even record the stream with the MediaRecorder API. If you'd rather send your webcam's video to a friend, Simple Video Chatting with WebRTC picks up right where this tutorial leaves off.
Before you go, here are a few things you can do:
-
Keep reading
Check out some related content:
-
Ask a question
Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.
Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇

