What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
To capture a website in a specific visitor state, open the site in the same browser context, add a valid cookie for that domain, reload or navigate to the target page, wait until the expected state is visible, and then take the screenshot. Selenium applies cookies to the current browsing context; Playwright adds them to a browser context. A cookie alone may not be enough when authentication also uses local storage, IndexedDB, session storage, passkeys, or server-side checks.
The examples below use authorized test accounts and placeholder values. Never copy a real production session cookie into source code or a shared artifact.
What must happen before the screenshot
- Start an isolated browser session. Use a fresh Selenium driver or Playwright browser context for a predictable state.
- Establish the cookie’s scope. Visit a page on the cookie’s host before calling Selenium’s
addCookie. The WebDriver Add Cookie command operates on the active document’s current browsing context. - Set or restore state. Add a cookie with the correct name, value, domain, path, expiry, Secure and SameSite expectations. For Playwright, add cookies to the context with either a URL or a domain/path pair.
- Navigate and render. Reload or open the target URL, then wait for an application-specific selector, URL, or other visible signal.
- Verify before capture. Check that a signed-in heading, selected preference, or other state marker is present. A screenshot taken immediately after setting a cookie can capture the pre-authenticated page.
- Capture the intended area. Choose a viewport, full page, or element screenshot deliberately, and save the result outside source control.
Cookie insertion is not an authentication bypass. The value must be valid, unexpired, correctly scoped, and accepted by the application. Follow the site’s documented test or login flow.
Selenium Java: add a cookie and capture a screenshot
Selenium Java exposes driver.manage().addCookie, getCookieNamed, getCookies, and deletion methods. The browser must first be on a page whose domain matches the cookie.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute#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 example
import java.io.File;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CookieScreenshot {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
driver.get("https://example.test/"); // establish the cookie domain
Cookie preference = new Cookie.Builder("preference", "compact")
.domain("example.test")
.path("/")
.build();
driver.manage().addCookie(preference);
// A session cookie would use the legitimate value from your test fixture.
// Cookie session = new Cookie.Builder("session", TEST_SESSION)
// .domain("example.test").path("/").isSecure(true).build();
// driver.manage().addCookie(session);
driver.navigate().refresh();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("[data-test='account-home']")));
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
System.out.println("Saved: " + screenshot.getAbsolutePath());
Cookie current = driver.manage().getCookieNamed("preference");
System.out.println("Cookie present: " + (current != null));
} finally {
driver.quit();
}
}
}
The simple host-only form is also valid after visiting the site: driver.manage().addCookie(new Cookie("key", "value"));. Use getCookies() to inspect the complete store, and deleteCookieNamed, deleteCookie, or deleteAllCookies to clean up test state.
Cookie attributes that commonly decide whether it works
| Attribute | What to check |
|---|---|
| Name and value | Use the exact names and a legitimate, current value from the test flow. Do not guess a session token. |
| Domain | A host-only cookie applies to the host that created it. A leading-domain scope may cover subdomains only when the application sets it that way. |
| Path | The request path must match. A cookie scoped to /app is not automatically sent to unrelated paths. |
| Expiry | An expired cookie is ignored. Omit expiry for a session cookie when that is what the application expects. |
| Secure | A Secure cookie is sent over HTTPS. Test with the same scheme used by the application. |
| HttpOnly and SameSite | These affect browser transmission and script access. They cannot be used to make an invalid authentication value valid. |
Element and alternative output capture
TakesScreenshot can capture the driver viewport or an individual WebElement. Selenium’s OutputType supports a file, Base64 text, or raw bytes, so choose the form that fits your report pipeline. Capture only after the state assertion; otherwise a valid image can still document the wrong visitor.
Playwright Java: isolate cookies in a browser context
Playwright separates browser contexts, making independent authenticated and anonymous runs straightforward. Add cookies to the context before creating or navigating the page. The API accepts a URL or a domain/path combination.
Complete context-based example
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class PlaywrightCookieScreenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions().setHeadless(true));
BrowserContext context = browser.newContext();
context.addCookies(new Cookie[] {
new Cookie("preference", "compact")
.setDomain("example.test")
.setPath("/")
});
Page page = context.newPage();
page.navigate("https://example.test/account");
page.locator("[data-test='account-home']")
.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("account.png"))
.setFullPage(true));
context.close();
browser.close();
}
}
}
For a URL-based cookie, use new Cookie("name", "value").setUrl("https://example.test") instead of setting domain and path. Playwright screenshots can target the viewport, the full page with setFullPage(true), or an element such as page.locator(".invoice").screenshot(...). The method can write an image file or return a byte array when no path is supplied.
Recommended Free Tools
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.
Reuse authenticated storage safely
Repeated login flows can be avoided by saving and restoring Playwright storage state. Storage state commonly includes cookies and local-storage data. Treat the resulting file as a credential: it may contain cookies or headers that permit account impersonation. Keep it outside version control, restrict filesystem permissions, use a short-lived test account, and delete it when the run ends.
Session storage is a separate case. A storage-state file does not automatically persist it; initialize the page with the session-storage data required by your application. IndexedDB, passkeys, and other identity mechanisms may likewise require the application’s supported setup rather than cookie injection.
Choosing Selenium or Playwright
| Need | More natural fit | Reason |
|---|---|---|
| Existing WebDriver grid, standard driver cookie controls | Selenium Java | Cookie management is attached to the driver and screenshots work through TakesScreenshot. |
| Several isolated identities in one browser process | Playwright Java | Each browser context has its own cookies and storage. |
| Full-page or element screenshots as a first-class option | Playwright Java | page.screenshot explicitly supports viewport, full-page, and element capture. |
| Existing Selenium-specific infrastructure | Selenium Java | Keeping the current stack avoids rewriting fixtures and grid integration. |
The cited API documentation does not establish a general performance winner. Decide based on your browser target, test infrastructure, authentication mechanism, and whether the image is a viewport, complete page, or one element.
Authentication state beyond cookies
- Cookies plus local storage: restore both when the application stores a token or feature flag in local storage.
- IndexedDB: some applications keep account data or tokens there; use the application’s supported test bootstrap.
- Session storage: initialize it separately for each page or context when required.
- Passkeys or hardware-backed identity: use a test credential or a supported automation flow rather than copying a cookie.
- Server-side session checks: IP, user agent, CSRF tokens, device binding, or reauthentication can invalidate an otherwise correctly shaped cookie.
After restoration, verify an application-owned signal such as an account menu, user name, selected preference, or redirect to the expected route. Do not infer success merely because the browser accepted the cookie.
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.
Troubleshooting cookie screenshots
“Unable to add cookie” or an invalid-cookie exception
In Selenium, navigate to the matching host first. Confirm that the cookie domain is compatible with the current document, the path is valid, and the value contains no illegal characters. In Playwright, use either a valid URL or a domain/path pair, not a mixture with incompatible scope.
The screenshot is still logged out
The value may be expired, scoped to another host or path, rejected by the server, or only one part of the application’s state. Inspect cookies with Selenium’s getters or the browser’s developer tools, then check local storage, IndexedDB, session storage, CSRF requirements, and the documented login flow. Add an explicit wait for the post-login selector rather than relying on a fixed short sleep.
The right page loads but the image shows a spinner
Wait for a stable, visible application selector or network-idle condition appropriate to the app. A page-load event does not guarantee that client-rendered content, images, or fonts are finished.
The capture contains the wrong portion
Use a normal driver screenshot for the viewport, Playwright’s full-page option for the document, or an element screenshot for a component. Check sticky headers and lazy-loaded content when comparing full-page images.
WebP output is required
Current Playwright Java release documentation describes WebP screenshot output, inferred from a .webp path or set explicitly where supported by the version you use. Confirm the exact option in your pinned release notes before relying on it in a pipeline.
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
State works locally but is unsafe to share
Remove authenticated state files from repositories and build logs. Store them in a protected workspace, rotate the test account, and limit who can download artifacts.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server when you want a rendered image without maintaining Selenium or Playwright setup. It accepts cookies and other request options through one HTTP call; its 63 options include full-page capture, CSS-selector element capture, custom JavaScript and CSS, waits, headers, cookies, user agents, timezone, geolocation, PDF output, and signed links.
For a direct capture, see the ScreenshotNeo API documentation:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Java can call the same endpoint with any HTTP client:
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.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
public class ScreenshotNeoJava {
public static void main(String[] args) throws Exception {
String url = "https://stripe.com";
String endpoint = "https://api.screenshotneo.com/v1/shot"
+ "?access_key=YOUR_API_KEY&url="
+ java.net.URLEncoder.encode(url, java.nio.charset.StandardCharsets.UTF_8);
HttpRequest request = HttpRequest.newBuilder(URI.create(endpoint)).GET().build();
HttpResponse response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() / 100 != 2) {
throw new IllegalStateException("Screenshot failed: " + response.statusCode());
}
Files.write(Path.of("shot.webp"), response.body());
}
}
Equivalent clients are:
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Before capture, ScreenshotNeo accepts cookie and 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 each response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Operational and cost considerations
- Use one fresh context per identity when tests could leak cookies between cases.
- Prefer explicit state assertions over arbitrary delays; this reduces flaky captures while preserving enough time for client rendering.
- Capture only after lazy content and required fonts or images have loaded.
- Keep cookies and storage-state files in secret-managed or short-lived workspaces.
- For API captures, inspect verdict and billing headers so failed pages are distinguishable from successful images and cache behavior.
- Do not claim a speed or success-rate advantage from these APIs; the available documentation describes behavior, not comparative benchmarks.
Frequently Asked Questions
Can I add a cookie before opening any page in Selenium?
No. Visit a page on the cookie’s matching domain first, then call addCookie in that active browsing context.
Should I use a cookie or a saved Playwright state file?
Use a cookie when that is the complete state your test needs. Use saved storage state for repeat runs that also depend on persisted local-storage data, while handling session storage separately.
How do I prevent an authenticated screenshot from leaking access?
Use a dedicated test account, protect cookie and storage-state files like credentials, exclude them from version control and logs, restrict artifact access, and rotate or revoke the account after testing.
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.

