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

To capture a webpage with JavaScript, first choose what you mean by “capture.” For a live screenshot of a tab or display, use navigator.mediaDevices.getDisplayMedia() and let the user choose and approve the surface. To record a video element, use HTMLMediaElement.captureStream() where supported, then pass its stream to MediaRecorder. These APIs capture rendered pixels or media streams; they do not serialize arbitrary page DOM into an image. For a still screenshot without a browser share chooser, use a screenshot service such as ScreenshotNeo.

Choose the capture route that matches the output

What you need JavaScript route Important constraint
A live capture of a tab, window, or display getDisplayMedia() The user chooses a surface and grants permission; the browser controls the chooser.
A recording of one video element video.captureStream() and MediaRecorder Support for captureStream() is limited and browser-dependent.
A still image of a selected display surface getDisplayMedia(), ImageCapture.grabFrame(), and canvas The still is a frame from the selected surface, not a direct DOM rendering.
A recording of an animation drawn to a canvas canvas.captureStream() and MediaRecorder Canvas origin-clean security restrictions apply.

Screen capture is permission-mediated, not a silent, unrestricted screenshot API. It generally requires a secure context such as HTTPS, and browser support and audio behavior vary. Confirm the APIs and output formats in the browsers you intend to support. See MDN’s Screen Capture API overview, getDisplayMedia() reference, and HTMLMediaElement.captureStream() reference.

Capture a tab or display as a live stream

Call getDisplayMedia() in response to a user action, such as a button click. The browser opens its own chooser; the user selects the tab, window, or display to share. When the promise resolves, attach the stream to a video element for preview. Provide a clear stop control and stop every track when capture ends.

Complete example: preview and stop a capture

<button id="startCapture">Choose what to share</button>
<button id="stopCapture" disabled>Stop sharing</button>
<video id="preview" autoplay playsinline muted></video>

<script>
  const startButton = document.querySelector("#startCapture");
  const stopButton = document.querySelector("#stopCapture");
  const preview = document.querySelector("#preview");
  let stream;

  startButton.addEventListener("click", async () => {
    try {
      stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
      preview.srcObject = stream;
      stopButton.disabled = false;

      // Also handle the browser's own “Stop sharing” control.
      stream.getVideoTracks()[0]?.addEventListener("ended", stopCapture, { once: true });
    } catch (error) {
      console.error("Display capture was not started:", error);
    }
  });

  function stopCapture() {
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      stream = null;
    }
    preview.srcObject = null;
    stopButton.disabled = true;
  }

  stopButton.addEventListener("click", stopCapture);
</script>

The video preview is muted to avoid audio feedback; muting the preview does not mean the captured stream has no audio. If audio is needed, request it with audio: true and check the target browser’s supported surfaces and audio behavior. The chooser and available options remain controlled by the browser. MDN’s screen-capture guide describes the flow and track cleanup.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Snagit 2024 - Screen Capture & Image Editor [PC/Mac Online Code]
  • Easily record quick videos of your screen and camera that offer the same connection as a meeting without the calendar wrangling
  • Draw on your screen as you record video with customizable arrows, squares, and step numbers to emphasize important information
  • Provide clear feedback and explain complex concepts with easy-to-use professional mark-up tools and templates
  • Instantly create a shareable link where your viewers can leave comments and annotations or upload directly to the apps you use every day
  • Version Note: This listing is for Snagit 2024. Please note that official technical support and software updates for this version are scheduled to conclude on December 31, 2026.

Permission, privacy, and lifecycle

  • Invoke the method from a user gesture and explain which surface the user should select. Do not build a flow that implies the page can capture a screen without consent.
  • Sharing a full display can expose passwords, messages, or other personal material. A logical surface may include content beyond what appears in the currently visible region.
  • Handle rejection: the user can cancel the chooser, deny permission, or encounter a browser or policy restriction.
  • Stop all stream tracks on completion, including when the user stops sharing from browser UI. Clear srcObject to release the preview reference.

Save one still image from the selected surface

For a still image, capture a frame from the display stream’s video track, draw it to a canvas, then encode it with toBlob(). The button below assumes the previous example has created a live stream; place it in the same script scope or adapt the event handler to your application.

Grab a frame and download it as PNG

async function saveStillFrame(stream) {
  const track = stream.getVideoTracks()[0];
  if (!track) throw new Error("The capture has no video track.");

  const imageCapture = new ImageCapture(track);
  const bitmap = await imageCapture.grabFrame();
  const canvas = document.createElement("canvas");
  canvas.width = bitmap.width;
  canvas.height = bitmap.height;

  const context = canvas.getContext("2d");
  if (!context) throw new Error("Could not create a 2D canvas context.");
  context.drawImage(bitmap, 0, 0);
  bitmap.close();

  const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
  if (!blob) throw new Error("The browser could not encode the image.");

  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "webpage-capture.png";
  link.click();
  URL.revokeObjectURL(link.href);
}

Call it from an explicit save button while capture is active, for example saveStillFrame(stream).catch(console.error). ImageCapture and capture-targeting features can vary by browser. Element Capture and Region Capture can narrow a capture in implementations that support them, but a moving or changing layout can affect the targeted area. Consult MDN’s Element and Region Capture guide and test the exact browser/version you ship against.

Rank #2
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
  • Record videos and take screenshots of your computer screen including sound
  • Highlight the movement of your mouse
  • Record your webcam and insert it into your screen video
  • Edit your recording easily
  • Perfect for video tutorials, gaming videos, online classes and more

Why this is not a DOM screenshot

The still above comes from a captured video frame. It reflects rendered output on the selected surface, rather than converting HTML nodes, styles, and assets directly into a bitmap. If your goal is a deterministic page screenshot without asking a visitor to share a screen, use a browser automation/rendering service instead of these user-facing display-capture APIs.

Capture and record a video element

HTMLMediaElement.captureStream() can create a stream of the rendered output of an <audio> or <video> element. Where the browser implements it, hand that stream to MediaRecorder. This captures the media element’s output; it is not a general capture of surrounding page layout. The method is marked limited availability by MDN, so do not assume it works in every widely used browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Debut Screen and Video Recorder Free [PC Download]
  • Screen capture software records all your screens, a desktop, a single program or any selected portion
  • Capture video from a webcam, network IP camera or video input device
  • Use video overlay to record your screen and webcamsimultaneously
  • Intuitive user interface to allow you to get right to video recording
  • Save your recordings to ASF, AVI, and WMV

Record a video element with MediaRecorder

async function recordVideoElement(video, durationMs = 5000) {
  if (typeof video.captureStream !== "function") {
    throw new Error("This browser does not support video.captureStream().");
  }
  if (typeof MediaRecorder === "undefined") {
    throw new Error("This browser does not support MediaRecorder.");
  }

  const stream = video.captureStream();
  const options = {};
  if (MediaRecorder.isTypeSupported("video/webm;codecs=vp9")) {
    options.mimeType = "video/webm;codecs=vp9";
  } else if (MediaRecorder.isTypeSupported("video/webm")) {
    options.mimeType = "video/webm";
  }

  const recorder = new MediaRecorder(stream, options);
  const chunks = [];
  recorder.addEventListener("dataavailable", event => {
    if (event.data.size > 0) chunks.push(event.data);
  });

  const stopped = new Promise((resolve, reject) => {
    recorder.addEventListener("stop", resolve, { once: true });
    recorder.addEventListener("error", event => reject(event.error), { once: true });
  });

  recorder.start();
  await new Promise(resolve => setTimeout(resolve, durationMs));
  recorder.stop();
  await stopped;

  const blob = new Blob(chunks, { type: recorder.mimeType || "video/webm" });
  stream.getTracks().forEach(track => track.stop());
  return blob;
}

// Example usage:
const video = document.querySelector("video#source");
const recording = await recordVideoElement(video, 5000);
const url = URL.createObjectURL(recording);
const download = document.createElement("a");
download.href = url;
download.download = "video-capture.webm";
download.click();
// Revoke the URL after the user no longer needs the file.
setTimeout(() => URL.revokeObjectURL(url), 60_000);

The example records for a chosen duration, collects the recorder’s chunks, then combines them into one Blob. A chunk emitted by dataavailable is not guaranteed to be independently playable; assembling the sequence is the safer approach. The selected MIME type is a request based on browser support, not a promise that every browser can encode every codec. The MediaStream Recording API reference explains recording stream data.

Playback and capture caveats

  • Make sure the source video is actually playing and producing frames before starting a time-limited recording; otherwise, the resulting file may be empty or shorter than expected.
  • Check MediaRecorder.isTypeSupported() for formats your application requests, and handle recorder errors rather than assuming one container works everywhere.
  • Test whether audio is present in the resulting stream in the browsers and media configurations you support.
  • If captureStream() is missing, this API route is not available in that browser. Choose a supported browser or a different capture approach rather than silently returning an empty recording.

Capture an animated canvas

When an animation is drawn into a canvas, canvas.captureStream(frameRate) returns a stream of canvas changes. The resulting stream can be recorded with MediaRecorder using the same chunk-collection pattern as above.

Rank #4
Debut Video Capture Software to Record from a Webcam, Computer Screen or Device [Download]
  • Capture video directly to your hard drive
  • Record video in many video file formats including avi, wmv, flv, mpg, 3gp, mp4, mov and more
  • Capture video from a webcam, network IP camera or a video input device (e.g.: VHS recorder)
  • Screen capture software records the entire screen, a single window or any selected portion
  • Digital zoom with the mouse scroll wheel, and drag to scroll the recording window
const canvas = document.querySelector("canvas#animation");
const stream = canvas.captureStream(30); // requested frame rate
const recorder = new MediaRecorder(stream);
const chunks = [];
recorder.addEventListener("dataavailable", event => {
  if (event.data.size > 0) chunks.push(event.data);
});
recorder.addEventListener("stop", () => {
  const blob = new Blob(chunks, { type: recorder.mimeType || "video/webm" });
  // Save or preview blob here.
  stream.getTracks().forEach(track => track.stop());
});
recorder.start();
// Later, when the user presses Stop:
recorder.stop();

Canvas pixel access and capture are subject to origin-clean restrictions. For example, drawing cross-origin images or video without the appropriate permission can taint a canvas; capture may then fail with a SecurityError. See MDN’s canvas.captureStream() reference and account for cross-origin sources before building the workflow around pixel access.

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

Or skip the browser setup

If you need a clean still of a webpage rather than a user-approved screen stream, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns an image or PDF; its browser-capture flow handles page rendering for you. Its API accepts familiar screenshot parameter names, which can make migration easier.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Capture Card, 4K HDMI Video Capture Card, Game Capture Card, 1080P 60FPS Video Capture Device, HDMI to USB 3.0 Capture Card for Streaming, Work with Camera/Xbox/PS4/PS5/PC/OBS
  • 【1080P HD High Quality】Capture resolution up to 1080p for video source and it is ideal for all HDMI devices such as PS4, PS3, Xbox One, Xbox 360, Wii U, DVDs, DSLR, Camera, Security Camera and set top box. Note: Video input supports 4K30/60Hz and 1080p120/144Hz. Does not support 4K120Hz/144Hz. Output supports up to 2K30Hz.
  • 【Plug and Play】No driver or external power supply required, true PnP. Once plugged in, the device is identified automatically as a webcam. Detect input and adjust output automatically. Won't occupy CPU, optional audio capture. No freeze with correct setting.
  • 【Compatible with Multiple Systems】suitable for Windows and Mac OS. High speed USB 3.0 technology and superior low latency technology makes it easier for you to transmit live streaming to Twitch, Youtube, Facebook, Twitter, OBS, Potplayer and VLC.
  • 【HDMI LOOP-OUT】Based on the high-speed USB 3.0 technology, it can capture one single channel HD HDMI video signal. There is no delay when you are playing game live.
  • 【Support Mic-in for Commentary】Rybozen capture card has microphone input and you can use it to add external commentary when playing a game. Please note: it only accepts 3.5mm TRS standard microphone headset.
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 API documentation for the request options and response details. Cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents using Claude, Cursor, or another MCP client take screenshots. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for free and get 1,000 screenshots a month with no card.

Troubleshoot common capture failures

Symptom Likely cause What to do
getDisplayMedia is undefined or unavailable The browser does not support the API in this context, or the page is not running in a secure context. Test in a supporting browser over HTTPS or localhost, and verify the target browser’s current API support.
The chooser does not open or capture is rejected The call was not initiated by a user gesture, the user canceled, or browser/policy permissions blocked it. Call from a visible button action, handle rejection, and explain that the user must select a surface.
The preview is black or does not start The stream was not attached, has ended, or has no video track. Check stream.getVideoTracks(), assign preview.srcObject, and handle the track’s ended event.
No sound appears in a screen recording The selected surface or browser does not provide an audio track, or audio capture was not requested. Request audio where appropriate and check the supported browser/surface combination; do not assume audio availability.
video.captureStream is not a function The target browser does not implement the limited-availability API. Feature-detect it and provide a supported alternative or browser requirement.
The recording Blob is empty or unplayable The source produced no frames, recorder events were not collected, or a chunk was treated as a complete file. Verify playback, collect non-empty dataavailable chunks, await the stop event, and combine chunks into a Blob.
Canvas capture throws SecurityError The canvas is not origin-clean, often because it includes cross-origin media. Use sources with appropriate cross-origin permission or avoid pixel/canvas capture of tainted content.
The selected page region shifts or is clipped Layout movement or changes in Element/Region Capture targeting affected the captured surface. Stabilize the layout where possible and test targeting in the browsers that implement those APIs.

Test the behavior you intend to ship

There is no single capture method that covers every output, browser, and permission model. Build a small compatibility matrix for the actual devices and browser versions your users rely on: test display selection, stop behavior, still-frame encoding, element capture, canvas origin rules, audio tracks, and recorder MIME types separately. Feature detection is more useful than assuming an API exists because a different route works in one browser.

Frequently Asked Questions

Can JavaScript take a screenshot of a webpage without asking the user?

The browser display-capture route described here requires the user to select and authorize a surface. For a service-generated webpage screenshot, use a screenshot API rather than treating getDisplayMedia() as a silent capture mechanism.

Can I screenshot a video element instead of recording it?

For a still, capture a frame from an approved display stream and draw it to canvas. The element captureStream() route produces a media stream, not a direct still-image serialization.

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.

Does captureStream() work in every browser?

No. HTMLMediaElement.captureStream() has limited availability; feature-detect it and test the browsers you need to support.

Quick Recap

Bestseller No. 2
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
Record videos and take screenshots of your computer screen including sound; Highlight the movement of your mouse
$19.99
Bestseller No. 3
Debut Screen and Video Recorder Free [PC Download]
Debut Screen and Video Recorder Free [PC Download]
Capture video from a webcam, network IP camera or video input device; Use video overlay to record your screen and webcamsimultaneously
Bestseller No. 4
Debut Video Capture Software to Record from a Webcam, Computer Screen or Device [Download]
Debut Video Capture Software to Record from a Webcam, Computer Screen or Device [Download]
Capture video directly to your hard drive; Screen capture software records the entire screen, a single window or any selected portion
$39.99

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.