How to Access Browser Camera in JavaScript Using getUserMedia
Use navigator.mediaDevices.getUserMedia() to request a camera stream and attach it to a <video> element. Serve the page over HTTPS or localhost, and allow camera access when prompted. This example opens a preview without a library and releases the camera when you click Stop:
<video id="preview" autoplay playsinline muted></video>
<button id="start">Start camera</button>
<button id="stop">Stop camera</button>
<p id="status"></p>
<script>
const preview = document.querySelector('#preview');
const status = document.querySelector('#status');
const start = document.querySelector('#start');
const stop = document.querySelector('#stop');
let stream;
stop.disabled = true;
start.onclick = async () => {
start.disabled = true;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
preview.srcObject = stream;
console.log('Actual settings:', stream.getVideoTracks()[0].getSettings());
status.textContent = 'Camera started';
stop.disabled = false;
} catch (error) {
console.error(error);
status.textContent = `Camera could not start: ${error.name}`;
start.disabled = false;
}
};
stop.onclick = () => {
stream?.getTracks().forEach(track => track.stop());
stream = null;
preview.srcObject = null;
status.textContent = 'Camera stopped';
stop.disabled = true;
start.disabled = false;
};
</script>
The browser chooses a camera for video: true. To prefer the rear camera on a phone, request video: { facingMode: { ideal: 'environment' } }; use user to prefer the front camera. These are preferences, so inspect the track’s getSettings() result to see what was actually selected. After permission is granted, enumerateDevices() can list available videoinput devices and their labels; request a selected camera with video: { deviceId: { exact: selectedDeviceId } }. Availability and labels depend on permission and browser privacy rules.
If the request fails, NotAllowedError can indicate denied permission or a permissions policy restriction; NotFoundError means no camera satisfies the request. NotReadableError can indicate a hardware or OS-level problem, including a camera that is already in use. On an insecure origin, navigator.mediaDevices may be unavailable, so use HTTPS or localhost. See the console’s actual error for diagnosis.
What you’ll build next: A camera viewer with source selection, resolution options, and frame capture using the optional Dynamsoft Camera Enhancer library.
Key Takeaways
getUserMedia()provides the native camera stream; stop its tracks when the preview is no longer needed.- Use
facingModefor a front or rear preference, orenumerateDevices()anddeviceIdfor a specific available camera. getSettings()reports the selected track settings; requested constraints are not necessarily the settings obtained.- Dynamsoft Camera Enhancer is an optional camera UI and frame-capture abstraction.
Common Developer Questions
How do I access the camera from a web browser using JavaScript getUserMedia?
Call getUserMedia({ video: true }) from a secure context, attach the returned stream to a video element, and stop its tracks when finished. The example above shows the complete native path.
Why does my browser camera access fail with NotAllowedError or NotFoundError?
Check the error name, camera permissions, and secure origin first. NotAllowedError can mean permission or policy denied access; NotFoundError means no device matches the requested constraints. A camera held by another application can instead produce NotReadableError.
How do I capture a video frame as an image from a browser camera stream?
Draw the video onto a canvas after its metadata is available, using videoWidth and videoHeight for the canvas dimensions. The optional Camera Enhancer example below uses getFrame() instead. For resolution tradeoffs, see high-resolution browser camera capture.
Prerequisites
Before getting started, make sure you have:
- A modern web browser (Chrome, Firefox, Safari, or Edge)
- A page served over HTTPS or localhost (required for camera access)
Step 1: Install the JavaScript Camera SDK
The SDK is available on npmjs.com. To include it directly in your HTML, add the following script tag:
<script src="https://unpkg.com/dynamsoft-camera-enhancer@2.1.0/dist/dce.js"></script>
To self-host the library, install it via npm:
npm i dynamsoft-camera-enhancer@2.1.0
Step 2: Open the Camera Stream in the Browser
Creating a web camera viewer using Dynamsoft Camera Enhancer (JavaScript edition) only requires two steps:
-
Add a container element to your HTML:
<div id="enhancerUIContainer" style="height: 100vh;"></div>Set the height to
100vhto make the camera viewer fill the entire screen. -
Initialize the camera viewer:
let enhancer = null; (async () => { enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); document.getElementById("enhancerUIContainer").appendChild(enhancer.getUIElement()); await enhancer.open(true); })();
At this point, your web camera viewer is ready. It includes a camera source selector, resolution options, and live preview — everything a web developer typically needs.
Step 3: Capture a Frame from the Camera Stream
If you want to capture a frame, use the getFrame() method.
Here’s an example of capturing a frame and displaying it in a popup window:
<button id="capture">Capture</button>
<script>
document.getElementById('capture').onclick = () => {
if (enhancer) {
let frame = enhancer.getFrame();
let width = screen.availWidth;
let height = screen.availHeight;
let popW = 640, popH = 640;
let left = (width - popW) / 2;
let top = (height - popH) / 2;
popWindow = window.open('', 'popup', 'width=' + popW + ',height=' + popH +
',top=' + top + ',left=' + left + ', scrollbars=yes');
popWindow.document.body.appendChild(frame.canvas);
}
};
</script>
Note:
The returned frame is not a Blob or buffer object. Instead, it is a custom type defined by Dynamsoft, and the actual image data is stored in an internal canvas element.
For continuous processing tasks like barcode scanning, object detection, or face recognition, you can use a timer to call getFrame() periodically.
Deploy Over HTTPS and Test Across Browsers
To deploy the project:
- Ensure the page is served over HTTPS, as camera access is restricted on insecure origins.
- You can use ngrok for HTTPS tunneling or host your project on GitHub Pages.
Test camera selection and preview behavior on your target browsers and devices; available cameras and exposed labels can vary by browser and permission state.
Here’s a screenshot from an iPad Pro:

Observed Browser and Device Behaviour
The output below was captured on November 9, 2026 on Windows 11 (build 26200) from localhost, in headless Chrome 156.0.8078.81 and headless Edge 157.0.4341.42. Two videoinput devices were registered: a USB Global Shutter Camera (32e4:0234) and a user-configured virtual camera. These are observations from one setup, not a compatibility matrix.
What enumerateDevices() returned
Before camera permission was granted, Chrome exposed only anonymous entries:
[
{ "kind": "videoinput", "label": "", "deviceId": "", "groupId": "" },
{ "kind": "audiooutput", "label": "", "deviceId": "", "groupId": "" }
]
After permission was granted, both browsers listed the real devices. Device and group IDs are opaque per-session hashes (abridged here):
videoinput "Global Shutter Camera (32e4:0234)" deviceId: 140eebc8… groupId: …
videoinput "Virtual Camera" deviceId: 608cac6f… groupId: …
audiooutput "Default - Q27P1B (NVIDIA …)" deviceId: default
Labels and usable deviceId values only appear after the user grants camera access, so a device picker cannot be populated meaningfully before that point. The virtual camera is a user-configured device: it is listed here as an enumeration fact only and is not used for any capability or resolution result in this article.
Observed outcomes
| Test | Chrome 156 | Edge 157 |
|---|---|---|
getUserMedia({ video: true }) with no permission |
NotAllowedError (“Permission denied”) |
— |
getUserMedia({ video: true }) after permission |
USB camera, 640×480 | USB camera, 640×480 |
video: { deviceId: { exact: 'no-such-device-id' } } |
OverconstrainedError |
OverconstrainedError |
track.readyState before / after stop() |
live → ended |
live → ended |
A successful call returned this track.getSettings() (abridged):
{
"width": 640,
"height": 480,
"frameRate": 30,
"aspectRatio": 1.3333333333333333,
"deviceId": "140eebc8…",
"groupId": "…",
"focusMode": "continuous",
"exposureMode": "continuous",
"whiteBalanceMode": "continuous",
"resizeMode": "none"
}
Two practical notes from these runs. The same video: true call is refused before permission and succeeds afterwards, so ask for permission before offering a device picker. And running several browser instances against one physical camera at the same time produced NotReadableError in our harness until the runs were serialized — the device was simply in use, not faulty.
Common Issues and Edge Cases
NotAllowedError: Check site permissions and any embedding page’s Permissions Policy. On an insecure origin,navigator.mediaDevicesmay be unavailable; use HTTPS orlocalhost.NotFoundError: No camera meets the requested constraints. Check that a camera is connected and try less restrictive constraints.NotReadableError: The camera could not be read after permission was granted. Check the OS camera permissions and close other applications using it.OverconstrainedError: A required constraint cannot be satisfied. Try anidealvalue rather than anexactresolution or device constraint.