October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
html2canvas

How to Add a Screenshot Button to a Web UI (Screen, Tab, Window, or DOM Element)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The right implementation depends on what the button should capture. Use navigator.mediaDevices.getDisplayMedia() when the visitor must choose a screen, application window, or browser tab. Use html2canvas when the target is a rendered element such as a card or report. Both approaches must start from a user click, and production code must explain what will be shared, handle permission failures, and stop capture tracks after creating the image.

Choose the capture scope first

Requirement Best fit What the user gets
Capture a monitor, app window, or browser tab Browser Screen Capture API A source picker and permission prompt, followed by a PNG of the selected surface
Capture one known element in your page html2canvas A canvas reconstructed from the page’s DOM and styles
Capture pages on your server, without a visitor picker Screenshot API such as ScreenshotNeo A rendered image or PDF returned by HTTP

Native display capture reflects the selected live surface, including content outside your document. DOM capture is more convenient for a specific component but cannot reproduce every browser-rendered effect or cross-origin resource.

Option 1: capture a selected screen, window, or tab

Complete HTML and JavaScript

Put the button in a page served over HTTPS (localhost is generally treated as secure for development). The call must happen directly from a transient user activation; browsers will not let a timer or page-load script open the picker.

<button id="screenShot" type="button">Take screenshot</button>
<p id="shotStatus" role="status"></p>

<script>
const button = document.querySelector('#screenShot');
const status = document.querySelector('#shotStatus');

button.addEventListener('click', async () => {
  if (!navigator.mediaDevices?.getDisplayMedia || !window.ImageCapture) {
    status.textContent = 'This browser cannot capture a display with this method.';
    return;
  }

  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('No video track was returned.');

    const imageCapture = new ImageCapture(track);
    bitmap = await imageCapture.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');
    });
    const objectUrl = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = objectUrl;
    link.download = `screenshot-${new Date().toISOString().replace(/[:.]/g, '-')}.png`;
    link.click();
    setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
    status.textContent = 'Screenshot downloaded.';
  } catch (error) {
    if (error.name === 'NotAllowedError') {
      status.textContent = 'Capture was cancelled or permission was denied.';
    } else {
      console.error(error);
      status.textContent = 'The screenshot could not be created.';
    }
  } finally {
    if (bitmap) bitmap.close();
    if (stream) stream.getTracks().forEach(track => track.stop());
    button.disabled = false;
  }
});
</script>

getDisplayMedia() opens the browser’s source chooser. ImageCapture.grabFrame() obtains one ImageBitmap without showing a video element; the canvas then encodes that frame as PNG. The finally block is essential: leaving tracks running can keep the capture indicator active and retain access to the selected surface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Amazon Basics Wired QWERTY Keyboard, Works with Windows, Plug and Play, Easy to Use with Media Control, Full-Sized, Black
  • KEYBOARD: The keyboard works for Windows with hot keys that enable easy access to Media, My Computer, Mute, Volume up/down, and Calculator
  • EASY SETUP: Experience simple installation with the USB wired connection
  • VERSATILE COMPATIBILITY: This keyboard is designed to work with multiple Windows versions, including Vista, 7, 8, 10 offering broad compatibility across devices.
  • SLEEK DESIGN: The elegant black color of the wired keyboard complements your tech and decor, adding a stylish and cohesive look to any setup without sacrificing function.
  • FULL-SIZED CONVENIENCE: The standard QWERTY layout of this keyboard set offers a familiar typing experience, ideal for both professional tasks and personal use.

Make the permission and privacy behavior explicit

  • Label the button and status text so visitors know whether they are saving a tab, window, or entire display.
  • Warn immediately beside the control that the selected surface may contain passwords, private messages, notifications, or other visible personal information. The user, not your script, chooses the source, but your UI should make the consequence clear.
  • Do not attempt to remember or silently reuse a prior choice. The browser requires interaction for each capture request.
  • Disable the button while the picker and encoding operation are in progress to prevent overlapping streams.

Permissions Policy and iframes

Top-level pages may use the API when the browser supports it. If your button lives in an iframe, the embedding document may need an allow="display-capture" attribute, and a site-wide Permissions Policy can require display-capture=(self). Without that policy allowance, the call can fail before the user sees a picker.

Browser support and graceful fallback

MDN marks display capture as “not Baseline,” meaning some widely used browsers do not support it. Feature-detect both getDisplayMedia and ImageCapture, show a useful message, and offer DOM capture or an uploaded image as a fallback. Do not promise that a single implementation works identically across desktop and mobile browsers.

Option 2: save a rendered DOM element with html2canvas

Install or load the library

For a page component, load html2canvas and call it with the element you want to reconstruct:

Rank #2
Sale
Logitech MK270 Full Size Wireless Keyboard and Mouse Combo - Black
  • Reliable Plug and Play: The USB receiver provides a reliable wireless connection up to 33 ft (1), so you can forget about drop-outs and delays and you can take it wherever you use your computer
  • Type in Comfort: The design of this keyboard creates a comfortable typing experience thanks to the low-profile, quiet keys and standard layout with full-size F-keys, number pad, and arrow keys
  • Durable and Resilient: This full-size wireless keyboard features a spill-resistant design (2), durable keys and sturdy tilt legs with adjustable height
  • Long Battery Life: MK270 combo features a 36-month keyboard and 12-month mouse battery life (3), along with on/off switches allowing you to go months without the hassle of changing batteries
  • Easy to Use: This wireless keyboard and mouse combo features 8 multimedia hotkeys for instant access to the Internet, email, play/pause, and volume so you can easily check out your favorite sites
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"></script>
<button id="cardShot" type="button">Save card as PNG</button>
<section id="capture">
  <h2>Quarterly report</h2>
  <p>Revenue increased 18%.</p>
</section>

<script>
document.querySelector('#cardShot').addEventListener('click', async event => {
  const button = event.currentTarget;
  button.disabled = true;
  try {
    const canvas = await html2canvas(document.querySelector('#capture'), {
      backgroundColor: '#ffffff',
      scale: window.devicePixelRatio
    });
    const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
    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();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  } catch (error) {
    console.error(error);
    alert('This element could not be rendered as an image.');
  } finally {
    button.disabled = false;
  }
});
</script>

html2canvas reconstructs the target from DOM and CSS; it does not take a photographic screenshot of the browser. Images and fonts from another origin need appropriate CORS headers, and unsupported CSS, plugins, video frames, or browser UI cannot be captured reliably. Test the exact components and browsers your users have.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Exclude controls from the image

Add data-html2canvas-ignore to buttons, menus, or other controls that should remain interactive on screen but not appear in the exported image:

<button data-html2canvas-ignore>Save card as PNG</button>

Output, sizing, and fidelity decisions

PNG versus other formats

PNG is lossless and preserves text and transparency well, but files can be large. If your workflow permits JPEG, pass 'image/jpeg' and a quality value to toBlob(); JPEG removes transparency and introduces compression artifacts. Native display capture in the example always writes PNG.

Rank #3
Sale
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
  • All-day Comfort: The design of this standard keyboard creates a comfortable typing experience thanks to the deep-profile keys and full-size standard layout with F-keys and number pad
  • Easy to Set-up and Use: Set-up couldn't be easier, you simply plug in this corded keyboard via USB on your desktop or laptop and start using right away without any software installation
  • Compatibility: This full-size keyboard is compatible with Windows 7, 8, 10 or later, plus it's a reliable and durable partner for your desk at home, or at work
  • Spill-proof: This durable keyboard features a spill-resistant design (1), anti-fade keys and sturdy tilt legs with adjustable height, meaning this keyboard is built to last
  • Plastic parts in K120 include 51% certified post-consumer recycled plastic*

Resolution and scaling

A display capture uses the selected surface’s frame dimensions. DOM capture uses the element’s CSS size multiplied by the chosen scale; device-pixel-ratio scaling improves sharpness but increases memory and encoding time. For very large reports, capture smaller sections or warn users before allocating a huge canvas.

Cross-origin content

Native capture can include whatever is visible in the selected tab or window, subject to browser privacy rules. html2canvas must fetch resources while reconstructing the DOM, so cross-origin images without CORS permission may be omitted or taint the canvas. Host assets on the same origin or configure the asset server’s CORS policy rather than trying to bypass it in client code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failures and fixes

Symptom Likely cause Fix
NotAllowedError or no picker The call was not made from a click, the user cancelled, or permission/policy blocked it. Call directly in the button handler, explain the prompt, check HTTPS, and configure iframe Permissions Policy.
“Not supported” message The browser lacks display capture or ImageCapture. Feature-detect and offer html2canvas or an upload fallback.
Black, blank, or wrong frame The track ended, no video track was returned, or the frame was read too early. Check getVideoTracks()[0], catch errors, and capture only after the stream resolves.
html2canvas image misses photos or fonts Cross-origin resources lack CORS headers or the resource is unsupported. Serve assets with CORS, use same-origin URLs, and test the component’s CSS.
Button remains unusable after an error Tracks or UI state were not cleaned up. Keep cleanup in finally; stop every track and re-enable the button.
Download does not start Blob creation failed or the object URL was revoked too soon. Check for a non-null blob, click an anchor, then revoke the URL after a short delay.

Testing and production checklist

  • Test HTTPS, localhost, desktop browsers, and the mobile browsers you support.
  • Verify cancellation, denied permission, missing APIs, ended tracks, and encoding failures.
  • Test a tab containing sensitive text and confirm your warning is visible before capture.
  • Check large canvases for memory pressure and long encoding times.
  • Confirm downloaded filenames, image dimensions, transparency expectations, and accessibility of status messages.
  • For iframes, verify the embedding page’s allow attribute and Permissions Policy.

Or skip the browser setup: ScreenshotNeo

When you need a screenshot of a URL from a backend, script, CI job, or AI workflow, ScreenshotNeo returns an image or PDF from one GET request. It accepts the cookie or consent banner before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and whether the request was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the parameter reference and options in the ScreenshotNeo documentation. The API supports full-page and element capture, lazy-image loading, dark mode, device presets or custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, pre-capture clicks, selector hiding, waits, request/resource blocking, headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification.

Rank #4
Redragon K521 Upgrade Rainbow LED Gaming Keyboard, 104 Keys Wired Mechanical Feeling Keyboard with Multimedia Keys, One-Touch Backlit, Anti-Ghosting, Compatible with PC, Mac, PS4/5, Xbox
  • 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
  • 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
  • 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
  • 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
  • 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use

cURL

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)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Every feature is available on every plan: Free includes 1,000 shots per month with no card; Starter is $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing gives two months free. Create a free ScreenshotNeo account to get 1,000 screenshots a month without a card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Security and privacy notes

A screenshot is an export of visible data. Avoid capturing secrets, redact sensitive fields before DOM capture, and tell users exactly where files are saved or uploaded. For native capture, never assume that selecting a tab excludes notifications or other visible content. For API capture, keep access keys server-side and treat returned images as potentially sensitive.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can a screenshot button capture the browser chrome or address bar?

No. Display capture can offer a screen, window, or tab, but browser-controlled chrome is generally excluded for privacy.

Best Value
Sale
Logitech K270 Full Size Wireless Keyboard for Windows - Black
  • All-day Comfort: This USB keyboard creates a comfortable and familiar typing experience thanks to the deep-profile keys and standard full-size layout with all F-keys, number pad and arrow keys
  • Built to Last: The spill-proof (2) design and durable print characters keep you on track for years to come despite any on-the-job mishaps; it’s a reliable partner for your desk at home, or at work
  • Long-lasting Battery Life: A 24-month battery life (4) means you can go for 2 years without the hassle of changing batteries of your wireless full-size keyboard
  • Simply plug the USB receiver into a USB port on your desktop, laptop or netbook computer and start using the keyboard right away without any software installation
  • Simply Wireless: Forget about drop-outs and delays thanks to a strong, reliable wireless connection with up to 33 ft range (5); K270 is compatible with Windows 7, 8, 10 or later

Can I capture a screen without asking the user?

No. getDisplayMedia requires a user gesture, source selection, and permission; it cannot silently reuse a stored choice.

Which method should I use for a dashboard export?

Use html2canvas for a known dashboard element when its assets are same-origin or CORS-enabled. Use display capture when the user must choose an entire tab or window.

How do I capture a URL in a server job instead of the visitor’s browser?

Use ScreenshotNeo’s HTTP API or MCP server; the cURL, Python, and Node.js examples above show the one-request workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 1
SaleBestseller No. 3
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Plastic parts in K120 include 51% certified post-consumer recycled plastic*; Product carbon footprint: 4.02 kg CO2e
$12.34
SaleBestseller No. 5
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Plastic parts in K270 include 38% certified post-consumer recycled plastic; Eight hot keys: For instant access to the Internet, e-mail, music volume and more
$21.48

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.