The right implementation depends on what you want to capture. To let a visitor choose an entire screen, window, or browser tab, attach a click handler to navigator.mediaDevices.getDisplayMedia(), grab one frame from the returned video track, encode it with a canvas, and download the PNG. To save a specific card, report, or other element already rendered in your page, use a DOM-rendering library such as html2canvas.
Both approaches are demonstrated below, including permission handling, privacy safeguards, browser and iframe requirements, cleanup, and production troubleshooting.
Choose the capture model first
| Requirement | Best fit | What the user experiences | Main limitation |
|---|---|---|---|
| Capture a monitor, window, or browser tab | Native Screen Capture API | A browser picker asks the user to select a source and approve sharing. | Requires a supported browser, HTTPS, and a fresh user gesture each time. |
| Capture one known element such as a card or invoice | html2canvas or a similar DOM renderer | Your button immediately renders the selected element to a canvas. | It reconstructs the DOM; it is not a pixel-perfect capture of every browser feature. |
Do not use display capture when you only need your own component: asking for a whole tab or monitor creates unnecessary permission and privacy friction. Conversely, a DOM library cannot give a user a screenshot of an arbitrary window or desktop.
Option 1: capture a selected screen, window, or tab
This native flow must start from a real button activation. The browser will not allow a timer, page load, or background callback to open the source picker. The user chooses what to share and must make that choice again for later captures; a previous approval cannot be silently reused.
#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.
Complete HTML and JavaScript example
The following example captures one frame without displaying a video preview. It disables the button during the operation, reports expected errors, downloads a PNG, closes the bitmap, and stops every media track in a finally block.
<button id="screen-shot" type="button">Take screenshot</button>
<p id="screen-status" role="status" aria-live="polite"></p>
<script>
const button = document.querySelector('#screen-shot');
const status = document.querySelector('#screen-status');
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Choose a screen, window, or tab in the browser dialog.';
let stream;
let bitmap;
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: false
});
const track = stream.getVideoTracks()[0];
if (!track) throw new Error('The selected source did not provide a video track.');
const capture = new ImageCapture(track);
bitmap = await capture.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 => {
if (result) resolve(result);
else reject(new Error('The browser could not encode the screenshot.'));
}, 'image/png');
});
const downloadUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = 'screenshot.png';
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(downloadUrl);
status.textContent = 'Screenshot downloaded.';
} catch (error) {
if (error.name === 'NotAllowedError') {
status.textContent = 'Capture was cancelled or permission was denied.';
} else if (error.name === 'NotFoundError') {
status.textContent = 'No capturable screen, window, or tab was available.';
} else {
console.error(error);
status.textContent = 'Screenshot failed. Check the console for details.';
}
} finally {
if (bitmap) bitmap.close();
if (stream) stream.getTracks().forEach(track => track.stop());
button.disabled = false;
}
});
</script>
How the capture pipeline works
- User gesture: the click handler calls
getDisplayMedia()directly. - Source selection: the browser presents its own picker for a display, window, or tab and requests permission.
- Frame acquisition:
ImageCapture.grabFrame()returns anImageBitmapfrom the video track, so no visible video element is required. - Encoding: the bitmap is drawn at its native dimensions and converted to PNG with
canvas.toBlob(). - Download: a temporary object URL is attached to an
<a download>element, clicked, then revoked. - Cleanup: closing the bitmap releases its resources and stopping tracks ends the capture indicator and camera-like session.
Production details you should add
- Explain beside the button exactly what can be shared. A selected tab or display may visibly contain passwords, private messages, notifications, or customer data.
- Keep the button disabled until the promise settles, preventing overlapping pickers and duplicate downloads.
- Use an explicit filename such as
billing-report-2026-09-29.pngwhen the screenshot has a meaningful context. Sanitize user-derived names before assigning them todownload. - If you need a preview, set the returned stream on a muted
<video>element, wait for metadata, and still stop all tracks after the user takes the still image. - For a high-resolution display, the bitmap dimensions can be large. Check canvas dimensions and memory use before adding annotations or multiple copies.
Security, permissions, and browser requirements
Secure context and activation
getDisplayMedia() is restricted to secure contexts, so serve the page over HTTPS (localhost is generally treated as secure for development). The call must be made while handling a transient user activation. Calling it from setTimeout, an automatic page effect, or a promise chain that no longer has the click activation can fail even if the user previously approved sharing.
Permissions Policy and iframes
An embedded application may need display capture enabled by its Permissions Policy. Depending on your deployment, set a policy such as display-capture=(self) and, when embedding a child origin, include allow="display-capture" on the iframe. Without the policy, a correctly written button can still be blocked before the picker appears.
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.
Privacy and consent
The browser cannot know which pixels the user considers private. Put a short warning near the control, for example: “Choose only the tab or window you intend to share; visible messages and credentials will be included.” Never imply that your application can filter content from a monitor capture after the fact. If your workflow handles sensitive data, offer the element-only method as the safer default.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOption 2: save a rendered element with html2canvas
When the target is a known element, load html2canvas and render that node. The result is a canvas that you can download as PNG. Mark controls that should not appear with data-html2canvas-ignore.
<button id="card-shot" type="button">Save card as PNG</button>
<section id="capture">
<h2>Quarterly report</h2>
<p>Revenue and retention summary</p>
<button data-html2canvas-ignore>Edit</button>
</section>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
document.querySelector('#card-shot').addEventListener('click', async event => {
const button = event.currentTarget;
const target = document.querySelector('#capture');
button.disabled = true;
try {
const canvas = await html2canvas(target, {
backgroundColor: '#ffffff',
scale: window.devicePixelRatio
});
canvas.toBlob(blob => {
if (!blob) throw new Error('PNG encoding failed.');
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'quarterly-report.png';
link.click();
URL.revokeObjectURL(url);
}, 'image/png');
} finally {
button.disabled = false;
}
});
</script>
This is DOM reconstruction rather than a screenshot of the compositor output. Complex filters, video, browser UI, plug-ins, and cross-origin resources may differ from what the user sees. Images and fonts loaded from another origin need an appropriate CORS configuration; otherwise the canvas may be tainted or the asset may be omitted. Test charts, web fonts, pseudo-elements, sticky regions, and lazy content at the dimensions your users actually use.
Controlling what appears
- Add
data-html2canvas-ignoreto buttons, menus, selection handles, or other controls that should remain interactive on screen but not in the exported image. - Clone or temporarily style a print-oriented version when the live component contains animations or hover states.
- Wait for images and fonts to finish loading before rendering. For a report that expands asynchronously, wait for its own “ready” state rather than using an arbitrary short delay.
- Use
toBlob()for downloads and uploads; reservetoDataURL()for small images that must be embedded directly in a string.
Native capture versus DOM rendering
| Axis | Native display capture | html2canvas |
|---|---|---|
| Capture scope | User-selected display, window, or tab | A DOM element you select in your page |
| Permission friction | Picker and permission prompt every time | No screen-sharing prompt |
| Fidelity | Pixels as presented by the selected surface | Reconstructed from DOM, styles, and loadable resources |
| Cross-origin behavior | Captures the selected surface without your script reading its page contents | Cross-origin images and fonts require CORS cooperation |
| Output | Canvas encoding lets you choose PNG, JPEG, or another supported type | Canvas encoding provides the same format choices |
| Cleanup | Stop every media track and close the bitmap | Release object URLs and avoid retaining large canvases |
Common failures and fixes
“getDisplayMedia is not a function”
The page is running in an unsupported browser or an insecure context. Move the deployment to HTTPS, verify the browser version you support, and provide an element-capture fallback where practical. The API is not supported uniformly across widely used browsers.
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.
The picker never opens
Check that the call occurs directly inside the click or keyboard activation handler. Also inspect the iframe’s Permissions Policy and its allow attribute. A policy denial can look like an ordinary permission failure.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsNotAllowedError
The user may have cancelled the picker, denied permission, or the browser may have rejected a call that lacked transient activation. Keep the message non-alarming and let the user retry from the button.
NotFoundError or an empty track
No capturable source was available, or the selected source ended before the frame was read. Confirm that you select a screen, window, or tab, check getVideoTracks()[0], and handle a track that ends unexpectedly.
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
The downloaded image is blank
Ensure the track is live before calling grabFrame(). If you render a DOM element, wait for images, fonts, and asynchronous data, and inspect whether a cross-origin resource tainted the canvas.
The element image looks different from the page
That is expected when a DOM renderer cannot reproduce a browser feature. Simplify filters and animations, provide CORS-enabled assets, set an explicit background, and compare at the same viewport and device-pixel ratio. Use native tab capture when exact visible pixels matter.
Free tools Windows power users keep installed
One-click scans. No signup required.
Memory or performance spikes
Large retina canvases consume memory proportional to width times height. Avoid retaining the bitmap and canvas after download, process one capture at a time, and consider a lower scale or a server-side capture for very large pages.
Best 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.
Testing checklist
- Test keyboard activation as well as a mouse click.
- Test cancellation, denied permission, missing policy, and a source that ends early.
- Verify that every track stops when encoding fails.
- Check the downloaded dimensions, filename, transparency or background, and color appearance.
- Test a page with cross-origin images, web fonts, lazy content, and an iframe.
- Confirm that privacy text is visible before the browser picker opens.
Or skip the browser setup
For automated or server-side screenshots, ScreenshotNeo provides a website screenshot API and MCP server. One request returns a PNG, JPEG, WebP, or PDF, so your application does not need to open a browser or ask an end user to share a screen.
With the API, cookie and consent banners, newsletter popups, and chat widgets are accepted or removed before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and whether the shot was billed. AI agents can use the MCP tools take_screenshot, get_page_info, and capture_pdf.
One-call example
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for options such as full-page lazy-image loading, CSS-selector element capture, device presets, retina scale, custom CSS or JavaScript, click actions, waits, blocked requests, headers, cookies, geolocation, PDF settings, caching, signed links, asynchronous webhooks, bulk capture, and usage reporting.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try the API.
Frequently Asked Questions
Can a screenshot button capture the browser’s address bar or other browser chrome?
No. Display capture can include a selected monitor, window, or tab, but web pages cannot programmatically read browser chrome. The user controls the source in the browser picker.
Can I capture a screen without showing a permission prompt?
No. Screen capture is intentionally user-mediated, and a page cannot silently reuse a stored approval. Use server-side URL capture when you need unattended screenshots.
Should I use PNG or JPEG?
PNG is the safer default for text, interfaces, and transparency. JPEG can produce smaller files for photographic content but introduces compression artifacts; choose it when that trade-off is acceptable.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →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.

