What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
You can start html2canvas() while a page is leaving, but beforeunload cannot guarantee that an asynchronous render or upload will finish. For a screenshot you cannot lose, start the capture from your own navigation action and await both rendering and persistence before changing location. Use visibilitychange to hidden as a best-effort last chance, with pagehide as a navigation-oriented fallback. Keep beforeunload for its intended purpose: warning about unsaved changes.
The reliable pattern
html2canvas returns a Promise. The browser may terminate a document before that Promise resolves, and lifecycle events are not dispatched consistently during mobile termination, browser crashes, force-quits, or process shutdown. Therefore, a lifecycle handler can trigger an opportunistic capture, but it is not a completion guarantee.
The strongest approach is:
- Capture before you initiate navigation.
- Await the html2canvas Promise.
- Persist the resulting image while the document is still active.
- Only then assign
location, submit the form, or perform another navigation.
For navigation you do not control, listen for visibilitychange and begin a guarded, best-effort capture when the document becomes hidden.
Which browser event should you use?
| Signal | What it means | Use for | Important limitation |
|---|---|---|---|
visibilitychange to hidden |
The document became hidden, for example because the user changed tabs or left the page. | Saving state and triggering a final, best-effort capture. | It can mean a tab switch, and does not keep rendering or network requests alive. |
pagehide |
The browser is hiding the page, commonly for history navigation. | Navigation-specific handling or a fallback. | Some mobile termination paths do not fire it. |
beforeunload |
The document is about to unload and may have unsaved work. | A conditional unsaved-changes warning. | Prompts require sticky user activation; it is unreliable on mobile and can prevent Firefox back/forward-cache use. |
unload |
Resource unloading. | None for screenshot persistence. | Often does not fire and can harm back/forward-cache behavior. |
Install and call html2canvas in the page
html2canvas is a browser-side library, not a native pixel screenshotter or a Node.js renderer. It reconstructs an image from the DOM and supported CSS, so the result can differ from what the browser visually paints.
Recommended Free Tools
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
async function renderPage() {
const canvas = await html2canvas(document.documentElement, {
useCORS: true,
backgroundColor: null,
logging: false
});
return canvas;
}
</script>
Pin the version you deploy and verify the library’s browser support for your target browsers. Capture a smaller container instead of document.documentElement when the use case permits; less DOM and fewer resources generally means less work, although the exact gain depends on the page and device.
Best-effort capture when the user leaves
This implementation starts only once, waits for the render, checks that a canvas exists, and then calls an application-owned persistence function. The visibility event is an opportunity, not a promise.
let captureStarted = false;
async function capturePage() {
if (captureStarted) return;
captureStarted = true;
try {
const canvas = await html2canvas(document.documentElement, {
useCORS: true,
logging: false
});
if (!canvas || canvas.width === 0 || canvas.height === 0) {
throw new Error("html2canvas returned an empty canvas");
}
await saveCanvas(canvas);
} catch (error) {
captureStarted = false;
console.error("Page capture failed", error);
}
}
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
void capturePage();
}
});
async function saveCanvas(canvas) {
const blob = await new Promise((resolve, reject) =>
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not encode image")), "image/png")
);
// Replace this with your own IndexedDB, service-worker, or upload flow.
// Do not assume a fetch will finish after navigation starts.
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = objectUrl;
link.download = "page-before-leave.png";
link.click();
URL.revokeObjectURL(objectUrl);
}
A download is only one persistence option. IndexedDB, a service worker, or an already-established application endpoint may be more appropriate. Critical application state should be saved continuously or before the navigation action, rather than waiting for this final callback.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Capture before navigation you control
If a button, router, or form handler causes the navigation, stop it, capture, persist, and continue only after success (or an explicit timeout policy).
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →let leaving = false;
async function captureThenNavigate(url) {
if (leaving) return;
leaving = true;
try {
const canvas = await html2canvas(document.querySelector("main"), {
useCORS: true,
logging: false
});
await saveCanvas(canvas);
window.location.assign(url);
} catch (error) {
leaving = false;
console.error("Capture prevented navigation:", error);
// Decide whether to keep the user on the page or navigate without a shot.
}
}
document.querySelector("#leave-link").addEventListener("click", event => {
event.preventDefault();
void captureThenNavigate(event.currentTarget.href);
});
Do not make the user wait indefinitely. Add an application-defined timeout around persistence, report failure visibly, and choose whether the screenshot is mandatory or optional for that workflow.
Why beforeunload is a poor screenshot hook
It is designed for a warning
beforeunload exists mainly to ask whether the user wants to stay because unsaved changes may be lost. A prompt requires prior user activation, and browsers display generic text rather than arbitrary message content.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
The event is not universal
Mobile browsers can terminate a page without dispatching it. A browser close, operating-system kill, crash, or power loss cannot be converted into a guaranteed asynchronous save point by adding a handler.
It can interfere with caching
Using beforeunload unnecessarily can make a page ineligible for Firefox’s back/forward cache. Prefer visibility-based state preservation and remove the listener when no unsaved changes remain.
html2canvas limitations that affect the output
- It builds an image from DOM information and supported CSS; it does not capture the browser’s final pixels, so visual differences are expected.
- Cross-origin images can be omitted or taint the canvas. A tainted canvas cannot be exported with
toDataURL()ortoBlob(). - Content inside a cross-origin iframe cannot be read because of browser security policy.
- CSS support varies. Test the exact fonts, filters, pseudo-elements, videos, sticky elements, and blend modes your page uses.
- A proxy can make suitable image resources accessible, but it is an additional engineering dependency and does not bypass browser content policy generally.
- Lazy images or content that has not rendered yet may be missing. Wait for the relevant selector, image completion, or your application’s own ready signal before calling html2canvas.
Performance and reliability practices
- Capture the smallest useful element and avoid unnecessarily tall pages.
- Use an idempotency flag so multiple visibility or page lifecycle signals cannot start competing renders.
- Await the Promise and handle rejection; persist only after a real canvas is available.
- Do not begin a large upload after navigation has started. If the result is important, upload before changing location or queue it in storage that your application controls.
- Keep lifecycle work optional. Save the underlying data during normal interaction so a missed event does not destroy the user’s work.
- Test on desktop and mobile, including tab switching, back navigation, reload, app switching, and process termination. No general success rate or completion time can be promised for unload-time work.
Troubleshooting
The screenshot is blank or incomplete
Capture after the page’s own ready condition, wait for lazy content, and target a specific container. Check the console for rejected resources and verify that the element has non-zero dimensions.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Images are missing or export throws a security error
Confirm that image responses permit cross-origin use and that the image element has the appropriate CORS configuration before loading. Otherwise host the asset on the same origin or use a carefully controlled proxy. Cross-origin iframes remain inaccessible.
The file never saves before leaving
This is expected when relying only on beforeunload, pagehide, or a late network request. Move capture into the click/router flow and await saveCanvas; retain the visibility handler only as a fallback.
The handler runs twice
Use one shared function and an idempotency guard as shown. Reset the guard only after a handled failure, not after a successful persistence operation.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Navigation feels stuck
Limit the capture region, set a timeout, and make the screenshot optional where appropriate. Explain the failure and provide a normal navigation path rather than waiting forever.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo captures a URL outside the page’s unload lifecycle. Its API accepts one GET request and returns PNG, JPEG, WebP, or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Equivalent 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)
Equivalent 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(`${res.status} ${res.statusText}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));
See the ScreenshotNeo documentation for authentication and options. Every plan includes the features: full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work.
| Plan | Allowance | Price |
|---|---|---|
| Free | 1,000 shots/month | No card |
| Starter | 3,000 shots | $5 |
| Growth | 15,000 shots | $15 |
| Pro | 60,000 shots | $39 |
| Scale | 250,000 shots | $99 |
| Business | 1,000,000 shots | $249 |
Yearly billing gives two months free. Start with 1,000 free screenshots a month without a card.
Frequently Asked Questions
Can html2canvas capture a page after the tab is closed?
No. Once the document is terminated, JavaScript cannot guarantee that rendering, encoding, or uploading will finish. Capture before a controlled navigation or use the visibility event only as a best-effort fallback.
Does html2canvas work in Node.js?
The project’s getting-started guidance describes browser-side use; it is not a Node.js screenshot renderer. Use a browser-based service when the target page must be captured outside its own lifecycle.
Will visibilitychange always mean the user is leaving?
No. Switching tabs or minimizing the browser also changes visibility to hidden, so treat the handler as an opportunistic trigger rather than proof of navigation.
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.

