October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Element Capture

How to Prevent Screenshots of Specific Webpage Regions with JavaScript

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

Short answer: you cannot reliably stop someone from screenshotting content that your webpage has rendered. JavaScript can request a user-approved screen-sharing stream and, in supporting browsers, restrict that stream to an element or crop it to a region. It cannot disable screenshots taken with browser controls, operating-system tools, extensions, another device, or a camera. Treat displayed data as capturable, then reduce risk with authorization, minimization, and watermarking.

What JavaScript can and cannot control

A browser page runs inside a security boundary. The page can manipulate its DOM, respond to events, and call APIs that the browser exposes. It does not receive a general-purpose “block screenshots” switch. The Screen Capture API is designed for sharing a display surface, not suppressing capture.

navigator.mediaDevices.getDisplayMedia() asks the user to choose a screen, window, or tab and returns a MediaStream. The permission prompt, source selection, and browser UI remain under the user agent’s control. A page cannot silently select a source or revoke the operating system’s screenshot function.

  • Blocking the context menu, disabling text selection, intercepting common screenshot-key shortcuts, or hiding an overlay after a suspected shortcut is only friction. It is not a security control and can be bypassed.
  • A Permissions-Policy: display-capture header or iframe policy can prevent your document from starting the Screen Capture API. It does not disable screenshots made outside that API.
  • Once confidential pixels are displayed, assume they can be copied. Enforce access on the server, show the minimum necessary data, expire sensitive views, and add a visible or forensic watermark when attribution matters.

Choose the real goal: prevent capture or constrain a shared stream

Most requests for “blocking a region” are actually one of two different problems. If the goal is to stop a person from saving what they see, ordinary JavaScript cannot guarantee it. If the goal is to build a screen-sharing or recording experience that includes only a particular part of your interface, the Screen Capture API has useful controls.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
CloudValley Laptop Camera Cover Slide, Metal 0.023 Inch Ultra-Thin, 2 Packs
  • Privacy Protection: CloudValley webcam cover is designed for those who prioritize privacy, security, and peace of mind when using laptops, tablets, and computers
  • Fashion Design: The space aluminum alloy webcam cover features a subtle design which compliments the beautiful aesthetic of top devices
  • Ultra-Thin Design: Measures only 0.023 (0.6 mm) inch thin, ensuring it does not interfere with closing your laptop or device while providing reliable camera coverage
  • Broad Compatibility: Works flawlessly with most laptops (MacBook, HP, Dell, Asus, Acer, Lenovo), All-in-One PCs and leading tablets including iPad, Surface Pro, Galaxy Tab, Fire HD, and Google Pixel Tablet
  • Simple to Use: Only need to align to the webcam, attach and press it firmly for 15 seconds. Does not interfere with web use or indicator light
Goal Appropriate technique What it does not do
Stop browser, OS, extension, or camera screenshots No reliable webpage-level JavaScript control It cannot make rendered content uncapturable
Let a user share a chosen display surface getDisplayMedia() Does not bypass the permission prompt or control other capture tools
Share one DOM subtree and its descendants Element Capture Only constrains the stream created for that sharing flow
Crop a stream to an element’s on-screen rectangle Region Capture Overlapping material can remain visible in the cropped area

Use getDisplayMedia for user-mediated capture

The basic flow must begin with a recent user gesture, such as a button click. It must run in a secure context (normally HTTPS), and browser support varies, so test the exact browsers your product promises to support.

  1. Render a clear “Share screen” or “Share tab” button.
  2. Inside the click handler, call navigator.mediaDevices.getDisplayMedia().
  3. Handle cancellation and permission errors without assuming that a stream was returned.
  4. Attach the returned stream to a video element or pass it to a recording or conferencing pipeline.
  5. Stop every track when sharing ends.
const shareButton = document.querySelector('#share');
const preview = document.querySelector('#preview');

shareButton.addEventListener('click', async () => {
  if (!window.isSecureContext || !navigator.mediaDevices?.getDisplayMedia) {
    console.error('Screen capture is unavailable in this browser or context.');
    return;
  }

  try {
    const stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    });

    preview.srcObject = stream;
    preview.play().catch(() => {});

    for (const track of stream.getVideoTracks()) {
      track.addEventListener('ended', () => {
        preview.srcObject = null;
      });
    }
  } catch (error) {
    if (error.name === 'NotAllowedError') {
      console.warn('The user denied capture or dismissed the picker.');
    } else {
      console.error('Screen capture failed:', error);
    }
  }
});

This code shares whatever surface the user selects. It does not prevent a separate screenshot of the page, and it does not let the page choose a tab without the user’s interaction and browser approval.

Element Capture: preserve one DOM tree

Element Capture is intended for a sharing flow where the stream should follow an eligible element and its descendants. It is the better conceptual match when you want to preserve a component’s DOM subtree rather than merely crop a rectangle on the screen.

The target has eligibility requirements. In particular, it needs to form a stacking context and be flattened in 3D space. A commonly used setup is isolation: isolate together with transform-style: flat; verify the current implementation and browser support before depending on it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Yilador Webcam Cover 3 Pack, 0.03 inch Ultra Thin Laptop Camera Cover Slide
  • Note: Not suitable for MacBooks released after 2023 or devices with a protruding front camera; Not applicable to full-screen or notch-style tempered glass screen protectors; Do not use on the rear camera of the phone.
  • 💻 Why Do You Need a Webcam Cover Slide? — Safeguard your privacy by covering your webcam with our reliable webcam cover when not in use. Don't let anyone secretly watch you. Stay protected!
  • ✅ Thin & Stylish — Enhance your laptop's functionality and aesthetics with our 0.027" ultra-thin webcam covers. Seamlessly close your laptop while adding a touch of sophistication.
  • ✅ Fits Most Devices — Compatible with laptops, phones, tablets, desktops! Keep your privacy intact on Ap/ple, Mac/Book, iPh/one, iP/ad, H/P, L/novo, De/ll, Ac/er, As/us, Sa/msung devices.
  • ✅ 365 Days Protection — Our upgraded 3.0 adhesive ensures a strong hold that won't damage your equipment. Experience reliable, long-term privacy protection day in and day out.
<section id="shareable" class="shareable">
  <h2>Project dashboard</h2>
  <canvas id="chart"></canvas>
</section>
<button id="share-element">Share this panel</button>
<video id="element-preview" autoplay muted playsinline></video>
.shareable {
  isolation: isolate;
  transform-style: flat;
}
const target = document.querySelector('#shareable');
const elementPreview = document.querySelector('#element-preview');

document.querySelector('#share-element').addEventListener('click', async () => {
  try {
    const stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    });

    // Element Capture APIs are not available in every browser build.
    // Feature-detect the implementation your target browsers expose.
    const RestrictionTarget = window.RestrictionTarget;
    if (!RestrictionTarget || !target.restrictTo) {
      stream.getTracks().forEach(track => track.stop());
      throw new Error('Element Capture is not supported here.');
    }

    const restrictionTarget = await RestrictionTarget.fromElement(target);
    await stream.getVideoTracks()[0].restrictTo(restrictionTarget);
    elementPreview.srcObject = stream;
  } catch (error) {
    console.error('Element sharing was not started:', error);
  }
});

Names and availability of the Element Capture methods have changed as the proposal has evolved. Keep the feature detection and test against the browsers you ship; do not use this path as evidence that screenshots are blocked.

Region Capture: crop to a geometric rectangle

Region Capture uses an element’s on-screen bounding box to crop the captured stream. It is useful when a conference or recording pipeline needs a rectangular area. Because it is geometry-based, content that overlaps that rectangle may still appear in the resulting stream. If the requirement is to follow one DOM tree and exclude other overlapping material, Element Capture is the closer fit.

const region = document.querySelector('#shareable');
const button = document.querySelector('#share-region');

button.addEventListener('click', async () => {
  try {
    const stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    });

    const cropTarget = window.CropTarget;
    const track = stream.getVideoTracks()[0];
    if (!cropTarget || !track.cropTo) {
      stream.getTracks().forEach(t => t.stop());
      throw new Error('Region Capture is not supported here.');
    }

    const target = await cropTarget.fromElement(region);
    await track.cropTo(target);
    document.querySelector('#region-preview').srcObject = stream;
  } catch (error) {
    console.error('Region sharing was not started:', error);
  }
});

Use Region Capture when a moving or resized rectangle is the thing you want to share. Recalculate or reapply the crop when your UI changes, and test scrolling, zoom, transforms, and overlapping elements. The crop affects this stream only; it does not alter what the user can screenshot locally.

Designing a safer page when screenshots are unavoidable

Minimize exposure

  • Fetch sensitive fields only after authorization and only for the view that needs them.
  • Mask account numbers, tokens, and personal data by default; reveal a field for a short, explicit action.
  • Expire sessions and revoke access server-side. Hiding a field with CSS is not equivalent to removing it from the DOM or API response.

Add attribution, not a promise

Place a user identifier, organization, timestamp, or case number in a visible watermark when policy permits. Watermarks can discourage casual redistribution and help identify a source; they cannot prevent a clean crop or a photograph.

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.
Rank #3
JOS California 9 Pack(3 Large + 3 Medium + 3 Small) 0.03 inch Ultra Thin Webcam Cover Slide Camera Blocker Protect Your Privacy Security for MacBook Air, Laptop, iPad, iMac, PC, iPhone
  • ✅Package included: California JOS (3Large+3Medium+3Small) webcam Privacy cover in Black color, All In One Solution in one Package, Assembly &Packed in USA !
  • ✅ Ultra-thin design by California JOS: Super thin design, perfect curve edges, and extra mini size, which means it can be perfectly combine with your devices. Webcam Cover is only 0.03 inches thick and does not feel its existence when the laptop lid is closed.
  • ✅ Universal Design by California JOS: Webcam Cover is compatible with most Laptop Computer, Smartphones, iPad,iphone, MacBook, MacBook Pro, Tablets PC, PS4 and all-in-one desktops. Many pieces package, meet your all cameras need.
  • ✅ Easy to Install: Use cloth to clean the surface of device's webcam, then remove adhesive tape from the back of the camera cover Slide, align the lens, and firmly press for 15 seconds to achieve a strong, Also, the adhesive can be easily applied and removed from the device without any traces.
  • ✅ Variety of sizes/shapes: Includes 9 pieces (3 large ovals, 3 medium rectangles, 3 standard ovals) in black color. A versatile solution for all your devices—laptops, tablets, phones, webcams, and more! With at least 3 options, it suits any situation. The large oval is specifically designed for the Tesla Model 3/Y interior cabin camera.

Keep capture controls understandable

Tell users exactly what will be shared, show a preview, provide a stop button, and stop tracks when the session ends. Do not disguise a sharing prompt as a screenshot blocker.

Permissions Policy and embedding

If an application must not initiate display capture, control that API permission at the document or iframe boundary:

Permissions-Policy: display-capture=()

An iframe can likewise be embedded without the display-capture permission. This is useful for governing your application’s use of the Screen Capture API, especially in embedded products. It does not disable the browser’s screenshot command, a native capture utility, an extension, or an external camera.

Common failures and fixes

Symptom Likely cause Fix
getDisplayMedia is undefined Insecure context or unsupported browser Serve the page over HTTPS, test a supported browser, and feature-detect before showing the button.
NotAllowedError User denied, dismissed, or the call was not triggered by a recent gesture Call from the click handler, explain the picker, and provide a retry path. Never retry in a loop.
The wrong area appears in Region Capture The crop follows the element’s bounding rectangle; overlap, transforms, zoom, or scrolling changed the geometry Inspect layout at the moment of capture, remove unintended overlap, and reapply the crop after significant layout changes.
Element Capture fails for a target The element does not meet stacking-context or 3D-flattening requirements, or the browser lacks the API Apply the required CSS, simplify transforms, feature-detect the methods, and fall back to ordinary display sharing with clear messaging.
Sharing stops unexpectedly The user stopped sharing in browser UI or the source ended Listen for the video track’s ended event, clear previews, and update application state.
A user can still take a screenshot That is outside the Screen Capture API’s scope Do not claim prevention. Reduce exposed data, authorize access, and watermark the rendered view.

Or skip the browser setup

If your actual requirement is to create clean screenshots of pages—not to stop a visitor from capturing them—ScreenshotNeo provides a one-request screenshot API and an MCP server for AI agents. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

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

Use the API documentation at https://screenshotneo.com/docs/ for the complete option list. A basic request is:

Rank #4
50 Pcs Webcam Cover Slide, 0.023 Inch Ultra-Thin Universal Laptop Camera Cover Slide for Laptop, Computer, Phone Protect Your Privacy and Security
  • Privacy Protection: Secure your personal space with this webcam cover, effectively blocking unwanted access to your laptop camera. This privacy barrier meets your personal stays confidential
  • Seamless Operation: With a user-friendly sliding mechanism, this laptop camera cover provides a smooth transition, allowing you to open or shut your camera effortlessly. Its intuitive design makes switching between privacy and use a breeze
  • Universal Fit: Designed to fit a most of devices, from laptops and desktops to smartphones, this webcam cover accommodates most standard camera sizes, offering consistent security across your tech gadgets
  • Robust Construction: Crafted from ABS materials, this cover is built to endure daily wear and tear. The front camera cover promises durability, meeting it remains functional and reliable over time without degradation
  • Elegant Aesthetics: Featuring a slim and modern design, this phone camera cover slide integrates naturally with your device's appearance. The webcam privacy cover adds a layer of security while maintaining a sophisticated look, perfect for those who value both functionality and style
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 supports full-page lazy-image capture, CSS-selector element shots, dark mode, device presets and custom viewports, retina scale, PDF settings, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, TTL caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.

Plan Included screenshots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card.

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

FAQ

Can CSS make one element impossible to screenshot?

No. CSS can change presentation or hide content, but it cannot control capture tools once pixels are rendered.

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

Does disabling screenshots in an iframe protect the parent page?

No. A Permissions Policy can restrict that iframe’s use of the Screen Capture API; it does not govern screenshots taken by the browser or operating system.

Best Value
Brvlsoc Vinyl Webcam Covers – Restickable Privacy Stickers for Laptop, Smartphone, Tablet, Smart TV & Game Console – Black, Multiple Sizes
  • Solid Black Privacy Protection: Keep your camera fully covered with these Brvlsoc vinyl webcam covers, designed in a sleek, solid black finish to discreetly protect your privacy across all your smart devices.
  • Multiple Sizes for All Devices: Comes in various sizes to fit everything from laptops and tablets to smartphones, smart TVs, and gaming consoles—providing full compatibility and coverage versatility.
  • Restickable & No Residue: These low-tack vinyl stickers are restickable, allowing multiple uses without leaving behind sticky residue or damaging your device surface.
  • Ultra-Thin & Durable Design: The covers are thin, flexible, and water-resistant, ensuring your device closes easily while maintaining lasting adhesion for everyday protection.
  • Safe & Non-Scratching: Made from smooth, soft vinyl that won’t scratch your screen or webcam lens, these reusable camera covers provide peace of mind without compromising functionality.

Which capture API should a sharing app choose?

Choose Element Capture for a DOM subtree, Region Capture for a geometric crop, and ordinary getDisplayMedia() when the user should choose the display surface. Confirm support and target eligibility in your supported browsers.

Frequently Asked Questions

Can CSS make one element impossible to screenshot?

No. CSS can change presentation or hide content, but it cannot control capture tools once pixels are rendered.

Does disabling screenshots in an iframe protect the parent page?

No. A Permissions Policy can restrict that iframe’s use of the Screen Capture API; it does not govern screenshots taken by the browser or operating system.

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

Which capture API should a sharing app choose?

Choose Element Capture for a DOM subtree, Region Capture for a geometric crop, and ordinary getDisplayMedia() when the user should choose the display surface. Confirm support and target eligibility in your supported browsers.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.