navigator.mediaDevices.getDisplayMedia() returns a live MediaStream, not an image file. To save one screenshot, request a user-selected display, read its video track with ImageCapture.grabFrame(), draw the resulting ImageBitmap on a canvas, and export the canvas with toBlob(). Always start the request from a user gesture, handle cancellation and browser errors, and stop every track when finished.
The complete browser workflow
The Screen Capture API is designed for sharing or recording a live stream. A still-image workflow has four stages:
- Call
getDisplayMedia()from a button click or another transient user-activation handler. - Take the selected stream’s video track.
- Use
ImageCapture.grabFrame()to obtain oneImageBitmap. - Draw it to a canvas and encode the canvas as PNG, JPEG or another supported image type.
The browser-controlled chooser lets the person select a display, window or tab. Script options can influence capture output, but cannot silently select or pre-filter a source on the user’s behalf.
Minimal runnable example
<button id="capture">Capture screenshot</button>
<a id="download" hidden>Download PNG</a>
<img id="preview" alt="Captured screen preview">
<script>
const button = document.querySelector('#capture');
const download = document.querySelector('#download');
const preview = document.querySelector('#preview');
let previousUrl;
button.addEventListener('click', async () => {
let stream;
let bitmap;
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: false,
preferCurrentTab: true
});
const [track] = stream.getVideoTracks();
if (!track) throw new Error('No video track was returned.');
bitmap = await new ImageCapture(track).grabFrame();
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const context = canvas.getContext('2d');
context.drawImage(bitmap, 0, 0);
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(result => result ? resolve(result) : reject(new Error('PNG encoding failed.')), 'image/png');
});
if (previousUrl) URL.revokeObjectURL(previousUrl);
previousUrl = URL.createObjectURL(blob);
preview.src = previousUrl;
download.href = previousUrl;
download.download = 'screen-capture.png';
download.hidden = false;
} catch (error) {
console.error(error);
alert(`Screenshot failed: ${error.name || 'Error'}${error.message ? ` — ${error.message}` : ''}`);
} finally {
if (stream) stream.getTracks().forEach(track => track.stop());
if (bitmap) bitmap.close();
}
});
</script>
The example revokes the previous object URL before replacing it, closes the bitmap, and stops all stream tracks. Those cleanup steps prevent an abandoned capture session or image resource from remaining active.
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Choosing capture options safely
A typical request is { video: true, audio: false }. Audio is unnecessary for a still and can trigger an additional sharing decision. preferCurrentTab: true can indicate that the current tab is preferred where the browser supports the option, but it does not force that choice.
getDisplayMedia() requires video. Passing video: false is invalid. Constraints and hints apply after the person chooses a source; they do not remove the browser’s chooser or let an application select a particular monitor or window without consent. The permission prompt can appear again for every request rather than being silently reused.
Capture dimensions and image format
The bitmap dimensions come from the selected track. Set the canvas to bitmap.width and bitmap.height to avoid stretching. PNG is lossless and suitable for UI text. For photographs or smaller files, encode as JPEG or WebP where the browser supports it:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(
result => result ? resolve(result) : reject(new Error('Encoding failed')),
'image/jpeg',
0. nueve
);
});
Replace the illustrative quality value with a number from 0 to 1 (for example, 0.9); PNG ignores the quality argument. If you need a deterministic file type across browsers, use image/png.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Capturing only an element or region
The ordinary flow captures the entire selected surface. Newer capture extensions can narrow the result after selection, but their support is more limited than basic screen sharing.
Element Capture
Element Capture isolates a chosen rendered DOM element and its descendants. Content from other page layers that overlaps the element is excluded. The documented pattern creates a restriction target from an element and calls track.restrictTo() before grabbing a frame. It requires support for both Element Capture and ImageCapture.grabFrame().
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Region Capture
Region Capture crops the tab to an element’s bounding rectangle. Unlike Element Capture, content from another layer that overlaps that rectangle can remain visible. Use Region Capture for geometric cropping; use Element Capture when DOM isolation and privacy are more important.
MDN describes Element and Region Capture as desktop-browser capabilities. Check current compatibility tables for the exact browser versions you support, and provide a fallback to whole-surface capture or a normal DOM screenshot method when the extensions are unavailable.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Permissions, policy and security
User activation
Invoke getDisplayMedia() directly inside a click, pointer or keyboard handler. Calling it later from an unrelated timer or background task can produce InvalidStateError. Do not attempt to bypass the chooser: screen sharing can expose passwords, private messages and other sensitive material.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Permissions Policy and iframes
If a site uses Permissions Policy, the parent document must allow display capture. For an embedded page, the parent can use:
<iframe src="/capture.html" allow="display-capture"></iframe>
The documented default allowlist for the display-capture directive is self. An iframe allowance enables the policy but never replaces the user’s source-selection prompt.
Error handling and troubleshooting
| Error or symptom | Likely cause | Fix |
|---|---|---|
InvalidStateError |
The call was not made during transient user activation, or the document is not in a usable state. | Start the request synchronously in a button handler and avoid calling it from a timer. |
NotAllowedError |
The user denied capture, the browser blocked it, or an enclosing policy disallows it. | Explain why access is needed, retry from a fresh gesture, and check iframe allow and Permissions Policy headers. |
NotFoundError |
No capturable source was available. | Ask the user to select an available display, window or tab and verify that the operating system permits screen recording. |
NotReadableError |
The selected source could not be read because of an OS, hardware or browser failure. | Close competing screen-recording software, retry, and test another source or browser. |
| No image after selection | The stream has no video track, the track ended, or frame capture is unsupported. | Check getVideoTracks(), listen for ended, test ImageCapture support, and show a fallback message. |
| Black or unexpected content | The user selected a different surface, a protected window, or a region with overlapping content. | Describe the required source before opening the chooser; use Element Capture rather than Region Capture when supported and privacy matters. |
| Memory growth after repeated captures | Old blob URLs, bitmaps or tracks were not released. | Call URL.revokeObjectURL(), bitmap.close(), and track.stop() in cleanup code. |
Recording versus one still image
Use the stream directly with MediaRecorder when the requirement is a video or live broadcast. Use grabFrame() and canvas encoding when you need a single PNG, periodic stills, thumbnails or an uploadable image. A stream remains live until its tracks end or you stop them; a bitmap is a detached snapshot that should be closed after use.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsBest Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Performance and reliability considerations
- Canvas memory grows with pixel count. A 4K capture requires substantially more memory than a laptop-sized tab, so resize only after deciding what detail your application needs.
- Do not keep a stream open while waiting for a user to download one frame. Capture once, stop the tracks and release the bitmap.
- For repeated frames, reuse a canvas where practical, but still close each
ImageBitmapand stop the stream when the session ends. - Expect the user to switch windows, minimize a source or stop sharing from browser controls. Monitor
track.onendedand disable capture controls when the track ends. - Use HTTPS (or a secure localhost origin) and test the exact desktop browsers your users run. Optional Element and Region Capture support varies.
Or skip the browser setup
If you need a website image rather than a user’s interactive screen, ScreenshotNeo makes a server-side capture with one request. It accepts cookie and consent banners before capture, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and bills only clean shots. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed; response headers report the page verdict and billing result.
See the ScreenshotNeo documentation for all options. A cURL request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.
Frequently Asked Questions
Can getDisplayMedia() save a PNG by itself?
No. It returns a live MediaStream. You must extract a video frame, draw it to a canvas and encode the canvas.
Can a site choose a monitor without showing a chooser?
No. Browser security keeps source selection under user control, and permission cannot be silently reused.
Is screen capture available in an iframe?
It can be, provided the embedding policy allows display capture, such as allow="display-capture"; the user still approves the source.
Why use Element Capture instead of Region Capture?
Element Capture isolates the element’s DOM content. Region Capture crops a rectangle and may include content from another layer that overlaps it.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

