Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To capture a cookie-personalized page in Java, install the cookie in the same browser session that opens the page and takes the screenshot. In Selenium, visit the cookie’s domain first, call driver.manage().addCookie(...), then navigate to (or refresh) the target URL. In Playwright, add cookies to a BrowserContext before creating or navigating a page. If an API login establishes the session, make that request through the same Playwright context so its cookie jar is shared.
What “using cookies” means for a screenshot
A screenshot tool does not inherit cookies from your normal Chrome profile unless you deliberately give it that browser state. The cookie must be present in the exact browsing context that performs navigation. A cookie sent to the wrong domain, path, or context is effectively absent.
Cookies also do not automatically bypass authentication controls, consent requirements, CSRF checks, bot defenses, or device binding. The target site decides whether a cookie is sufficient. Secure cookies require HTTPS, HttpOnly cookies cannot be read by page JavaScript, and SameSite rules can restrict when a cookie is sent.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Selenium Java: add a cookie before capture
Selenium’s cookie API applies to the current browsing context, and the driver must already be on a page in the cookie’s valid domain. A reliable sequence is:
#1 Best Overall
- Start a WebDriver instance.
- Navigate to the target origin or a lightweight page on that origin.
- Create an
org.openqa.selenium.Cookiewith the exact name, value, domain, path, expiry, and security attributes required by the site. - Call
driver.manage().addCookie(cookie). - Navigate to or refresh the screenshot URL.
- Save the image with Selenium’s screenshot API.
Complete Selenium example
import java.nio.file.Path;
import java.time.Duration;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CookieScreenshot {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
// Selenium requires a page on the relevant domain first.
driver.get("https://app.example.com/");
Cookie session = new Cookie.Builder("session", "REPLACE_WITH_SESSION_VALUE")
.domain("app.example.com")
.path("/")
.isSecure(true)
.isHttpOnly(true)
.build();
driver.manage().addCookie(session);
driver.get("https://app.example.com/account");
byte[] png = ((org.openqa.selenium.TakesScreenshot) driver)
.getScreenshotAs(OutputType.BYTES);
java.nio.file.Files.write(Path.of("account.png"), png);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Use the host-only form of the domain unless the site intentionally shares the cookie across subdomains. A cookie for example.com and one for app.example.com have different scope. Match the original path: a cookie scoped to /admin will not be sent to /account. If the server issued an expiry, reproduce it with Selenium’s expiry builder; otherwise a session cookie disappears when the browser closes.
Verify that Selenium actually has the cookie
Immediately after adding it, inspect the browser’s cookie store:
System.out.println(driver.manage().getCookieNamed("session"));
Then refresh the target page. If the page still shows a login form, inspect the browser’s network traffic or application response. The server may have rejected an expired token, required another cookie, bound the session to a user agent or IP, or required a CSRF token in addition to the session cookie.
Full-page and element screenshots in Selenium
The standard WebDriver screenshot captures the current viewport. For a specific element, locate it and use Selenium’s element screenshot support:
Rank #2
var panel = driver.findElement(org.openqa.selenium.By.cssSelector("#invoice"));
panel.getScreenshotAs(OutputType.FILE).renameTo(new java.io.File("invoice.png"));
Full-page output is browser- and driver-dependent. A common approach is to use a browser-specific full-page facility or scroll-and-stitch images; test the result on pages with sticky headers and lazy content.
Playwright Java: BrowserContext cookie scope
Playwright stores cookies in a BrowserContext. Every page created from that context receives the cookies you add, while another context remains isolated. You can provide either a URL or a domain and path.
Complete Playwright example
import com.microsoft.playwright.*;
import java.nio.file.Paths;
import java.util.List;
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(List.of(new Cookie("session", "REPLACE_WITH_SESSION_VALUE")
.setDomain("app.example.com")
.setPath("/")
.setSecure(true)
.setHttpOnly(true)));
Page page = context.newPage();
page.navigate("https://app.example.com/account");
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("account.png")));
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("account-full.png"))
.setFullPage(true));
Locator invoice = page.locator("#invoice");
invoice.screenshot(new Locator.ScreenshotOptions()
.setPath(Paths.get("invoice.png")));
browser.close();
}
}
}
Playwright can return bytes instead of writing a file by omitting setPath and using the returned byte array. Full-page mode captures the document’s full scrollable height; element screenshots isolate the selected node.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallWhen login is performed through an API
Use context.request() or page.request() for the login or setup call. Those requests share the context’s cookie jar and apply cookies received in responses to pages in that context. Creating an isolated APIRequest.newContext() intentionally keeps a separate jar, so a successful API login there will not authenticate a page in another context.
APIResponse login = context.request().post("https://app.example.com/api/login",
RequestOptions.create().setData("{"user":"alice","password":"..."}")
.setHeader("Content-Type", "application/json"));
if (!login.ok()) throw new RuntimeException("Login failed: " + login.status());
Page page = context.newPage();
page.navigate("https://app.example.com/account");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("account.png")));
For diagnostics, Playwright’s documented Request.allHeaders() method lets you inspect complete request headers when you need to confirm what was sent. Do not print session values in shared logs.
Rank #3
HtmlUnit: a lighter, GUI-less Java option
HtmlUnit provides a GUI-less Java browser implementation with cookie support, configurable request headers, JavaScript support, and Selenium WebDriver integration. It can be useful when a full Chromium or Firefox engine is unnecessary, but verify rendering and JavaScript compatibility against the target site.
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
try (WebClient client = new WebClient()) {
client.getOptions().setJavaScriptEnabled(true);
client.addCookie(new Cookie("app.example.com", "session",
"REPLACE_WITH_SESSION_VALUE", "/", null, true));
HtmlPage page = client.getPage("https://app.example.com/account");
System.out.println(client.getCookieManager().getCookies());
// Use a rendering/screenshot integration appropriate to your HtmlUnit setup.
}
WebClient.addCookie(...) and getCookies() manage state. The CookieManager can disable cookie handling when you need a deliberately stateless request. HtmlUnit’s own engine is not identical to a modern browser, so pages relying on advanced browser APIs may render differently.
Choosing the Java approach
| Approach | Browser fidelity | Cookie scope | Screenshot controls | Best fit |
|---|---|---|---|---|
| Selenium WebDriver | Drives installed browser engines | Current browsing context and valid domain | Viewport and element methods; full-page support varies by driver | Existing WebDriver suites and cross-browser testing |
| Playwright Java | Drives bundled browser engines | BrowserContext shared by its pages | File, byte buffer, full-page and element screenshots | Isolated sessions, deterministic capture and API-plus-page workflows |
| HtmlUnit | Own GUI-less Java implementation | WebClient/CookieManager | Depends on the rendering integration | Lightweight automation where browser fidelity is not critical |
Cookie failures: symptoms, causes and fixes
- “You may only add cookies for the current domain.” Navigate to the cookie’s origin before calling Selenium’s
addCookie; check that the host and scheme match. - The cookie appears in the store but the page is logged out. Confirm name, value, domain, path, expiry, Secure and SameSite requirements. The session may also require a second cookie or server-side device binding.
- Works in one Playwright page but not another. Ensure both pages came from the same
BrowserContext. Contexts are intentionally isolated. - API login succeeds, browser remains anonymous. Make the request with
context.request()orpage.request(), not an unrelatedAPIRequest.newContext(). - Consent banner or login overlay covers the capture. Handle the site’s consent flow or click the appropriate UI before capture; possessing a cookie is not proof that consent requirements were met.
- Blank, partial or stale screenshots. Wait for a selector, network completion and lazy images; increase the page-load timeout; disable animations with test CSS; and capture after the authenticated state is visibly rendered.
- HttpOnly cookie cannot be read in page JavaScript. That is expected. Browser automation can still send it; inspect the automation context or request headers instead of calling
document.cookie. - Parallel jobs leak authentication. Create one fresh context or WebDriver profile per account/job. Never reuse a mutable cookie jar across users.
Security, reliability and cost considerations
Treat cookie values as credentials. Load them from a secret manager or environment variable, restrict log output, use HTTPS, and delete temporary screenshots that contain personal data. Prefer short-lived test accounts and tokens. A deterministic capture pipeline should pin browser and driver versions, wait for a meaningful authenticated selector, and record the URL, viewport, browser version and timestamp alongside the image.
Retries help with transient navigation failures but can repeat state-changing requests. Retry screenshot navigation only after idempotent setup, and regenerate expired sessions rather than endlessly replaying an old cookie. For long pages, full-page images consume more memory; element captures or PDF output may be more practical for reports.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server when you do not want to maintain Selenium, Playwright or HtmlUnit. A single request can return PNG, JPEG, WebP or PDF. It accepts cookie and header options for the target request, while its cleaning steps remove cookie/consent banners, newsletter popups and chat widgets before capture; each step can be disabled.
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers identify the page verdict and whether it was billed. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients. Free usage includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorscurl -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 documentation for cookie, header and capture parameters. The same endpoint also supports JavaScript, custom CSS, waits, device and viewport settings, full-page capture, element selectors, blocking rules, signed links, async webhooks and bulk requests.
Create a free ScreenshotNeo account to get 1,000 screenshots each month without a card.
Java clients for the same ScreenshotNeo request
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}`);
Frequently Asked Questions
Can I add a Selenium cookie before calling driver.get() for the target page?
No. First navigate to a page on the cookie’s valid domain, then add the cookie and navigate to the target URL.
Best Value
Should I reuse my personal browser profile for automated screenshots?
Use a dedicated profile or isolated context instead. Personal profiles contain unrelated credentials and make captures non-reproducible.
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 →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Does a cookie guarantee an authenticated screenshot?
No. The server may require additional cookies, headers, CSRF tokens, device checks or an unexpired server-side session.
Which Java library is the safest default for modern JavaScript sites?
Playwright or Selenium, because both drive real browser engines. Choose based on your existing test stack and required browser coverage.
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.

