ScreenshotNeo

BlogHow-to

Use Cookies in Java Website Screenshot Requests

Add cookies to the same Java browser session that captures a page, with Selenium, Playwright, HtmlUnit, troubleshooting, and an API option.

By the ScreenshotNeo team30 September 20269 min read

Use Cookies in Java Website Screenshot Requests

To use a cookie in a Java screenshot, install it in the same browser session that will navigate to and capture the page. In Selenium, open the cookie’s domain first, call driver.manage().addCookie(...), then navigate or refresh the target URL. In Playwright, add the cookie to the BrowserContext before creating or navigating the page. A cookie sent to a different session, domain, path, or browser context cannot authenticate the screenshot request.

This guide covers Selenium WebDriver, Playwright for Java, Playwright API setup, and HtmlUnit, with complete examples and fixes for the failures that make screenshots look logged out.

Cookies are scoped state. The browser that sends the navigation request must own the cookie jar. A cookie copied into an HTTP client, another browser context, or a different domain does not automatically reach the page renderer.

The cookie must live in the same browser context that navigates and captures the page.
The cookie must live in the same browser context that navigates and captures the page.
  1. Determine the exact host, path, scheme, and security attributes for the cookie.
  2. Start one browser session or context.
  3. Navigate to a page on the target origin when the API requires it.
  4. Install the cookie in that session.
  5. Navigate to the final URL, wait for the authenticated UI, and capture.

Selenium documents addCookie as adding a cookie to the current browsing context and requires the driver to be on a matching domain first: Selenium cookie documentation. Playwright gives each BrowserContext its own storage; cookies added to that context are sent by all pages created from it: BrowserContext API.

Complete example

import java.nio.file.Path;
import java.time.Duration;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class CookieScreenshot {
  public static void main(String[] args) {
    String target = "https://example.com/account";
    String cookieHost = "https://example.com/";

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless=new", "--window-size=1440,1200");

    WebDriver driver = new ChromeDriver(options);
    try {
      // Selenium requires a page on the relevant origin before addCookie.
      driver.get(cookieHost);

      Cookie session = new Cookie.Builder("session_id", "REPLACE_WITH_REAL_VALUE")
          .domain("example.com")
          .path("/")
          .isSecure(true)
          .build();
      driver.manage().addCookie(session);

      driver.get(target);
      new WebDriverWait(driver, Duration.ofSeconds(20))
          .until(ExpectedConditions.presenceOfElementLocated(
              org.openqa.selenium.By.cssSelector("[data-user-menu]")));

      byte[] png = ((org.openqa.selenium.TakesScreenshot) driver)
          .getScreenshotAs(org.openqa.selenium.OutputType.BYTES);
      java.nio.file.Files.write(Path.of("authenticated.png"), png);
    } catch (Exception e) {
      throw new RuntimeException("Screenshot failed", e);
    } finally {
      driver.quit();
    }
  }
}

Replace the selector with an element that only appears for a signed-in user. Waiting for that signal is more reliable than sleeping for a fixed number of milliseconds.

Attribute What to check
Name and value Copy the exact value; URL encoding and case can matter.
Domain Use example.com for that host and its subdomains, or omit it for a host-only cookie. Do not set a cookie for a sibling domain.
Path The request path must match the cookie path. Use / when the site expects it globally.
Secure A secure cookie is sent only over HTTPS. Do not test it on HTTP.
Expiry Expired session cookies are ignored. Omit expiry for a session cookie.
SameSite Cross-site navigation rules can prevent a cookie from being sent even when it exists in storage.

For a host-only cookie, navigate to the exact host and build the cookie without a domain when your Selenium version permits it. If the application sets several related cookies (for example, a session plus a CSRF or preference cookie), install all of them before the final navigation.

3. Playwright Java: use a BrowserContext

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(
          new Browser.NewContextOptions().setViewportSize(1440, 1200));

      context.addCookies(List.of(
          new Cookie("session_id", "REPLACE_WITH_REAL_VALUE")
              .setDomain("example.com")
              .setPath("/")
              .setSecure(true)
      ));

      Page page = context.newPage();
      page.navigate("https://example.com/account");
      page.locator("[data-user-menu]").waitFor();
      page.screenshot(new Page.ScreenshotOptions()
          .setPath(Paths.get("authenticated.png"))
          .setFullPage(true));

      context.close();
      browser.close();
    }
  }
}

Instead of setDomain and setPath, a Playwright cookie can use setUrl("https://example.com/"). A context can contain multiple pages, and every page in that context receives the cookies. Playwright screenshots support a file path, a byte buffer, full-page capture, and element capture; see the Java screenshot guide.

Capture one element or return bytes

byte[] card = page.locator("main .invoice").screenshot();
java.nio.file.Files.write(java.nio.file.Path.of("invoice.png"), card);

byte[] fullPage = page.screenshot(new Page.ScreenshotOptions()
    .setFullPage(true));

When an API login sets a Set-Cookie response, use the page’s or context’s request client. Playwright documents that context.request() and page.request() share cookie storage with the browser context. A separately created APIRequest.newContext() intentionally has an isolated jar: APIRequestContext API.

try (Playwright playwright = Playwright.create()) {
  Browser browser = playwright.chromium().launch();
  BrowserContext context = browser.newContext();

  APIResponse login = context.request().post("https://example.com/api/login",
      RequestOptions.create().setData("{\"email\":\"user@example.com\",\"password\":\"secret\"}"));
  if (!login.ok()) throw new IllegalStateException("Login failed: " + login.status());

  Page page = context.newPage();
  page.navigate("https://example.com/account");
  page.screenshot(new Page.ScreenshotOptions().setPath(java.nio.file.Paths.get("account.png")));
}

Do not log passwords or session values. If you intentionally use an isolated API context, copy only the cookies you are authorized to use into the browser context with context.addCookies.

5. HtmlUnit: manage cookies in a GUI-less Java client

HtmlUnit provides cookie support, request headers, JavaScript controls, and Selenium WebDriver integration. Its WebClient and CookieManager hold state. It is useful when a full browser engine is unnecessary, but verify rendering and JavaScript behavior for the target site before relying on it.

import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class HtmlUnitCookies {
  public static void main(String[] args) throws Exception {
    try (WebClient client = new WebClient()) {
      client.getOptions().setJavaScriptEnabled(true);
      CookieManager manager = client.getCookieManager();
      manager.addCookie(new Cookie("example.com", "session_id",
          "REPLACE_WITH_REAL_VALUE", "/", null, true));

      HtmlPage page = client.getPage("https://example.com/account");
      System.out.println("Cookies sent: " + manager.getCookies());
      System.out.println(page.getTitleText());
    }
  }
}

HtmlUnit is primarily a headless page implementation; if you need a pixel screenshot, use Selenium or Playwright with the same cookie values (or HtmlUnit’s Selenium integration) and validate the resulting browser behavior.

6. Reuse cookies from a real login safely

For a login that requires MFA or a consent flow, complete it once in an authorized browser, then export the session state using the framework’s storage-state facilities. Keep the file secret, give it a short lifetime, and never commit it. A copied cookie does not bypass server-side authorization, CSRF checks, bot defenses, or expiry.

  • Confirm the cookie belongs to the same account and environment as the URL.
  • Preserve all cookies set during login, not only the first session cookie.
  • Check whether the site binds a session to IP, user agent, device, or a server-side token.
  • Refresh state after logout, password changes, or an expiry response.

7. Troubleshooting

Symptom Likely cause Fix
InvalidCookieDomainException The driver is on another host, or the domain is malformed. Navigate to the target origin first; use a domain without a scheme or path.
Cookie appears in storage but page is logged out Wrong path, expired value, missing companion cookie, or server-bound session. Inspect the browser’s cookie details, install every required cookie, and check the response status.
Cookie is not sent on HTTPS Secure or SameSite rules block it. Use the correct HTTPS URL and reproduce the site’s SameSite context.
Works in one Playwright page, not another Pages belong to different contexts. Create both pages from the same BrowserContext or add cookies to the new context.
API login succeeds but navigation is anonymous The API client has an isolated cookie jar. Use context.request() or copy its cookies into the browser context.
Screenshot is taken before login UI appears Navigation or JavaScript is still running. Wait for a user-only selector, URL state, or a specific network response; avoid arbitrary sleeps.
Blank or partial screenshot Page timeout, blocked resources, viewport or lazy loading. Set a realistic timeout, wait for the page’s ready signal, scroll or use full-page capture, and capture console/network errors.
CAPTCHA or bot-check page The site requires an interactive verification. Do not attempt to bypass it; use an authorized session or the site’s supported access method.

Inspect what the browser actually sends

In Playwright, listen to requests and use Request.allHeaders() when diagnosing headers and cookie presence: Request API. In Selenium, inspect driver.manage().getCookies() immediately after adding state, then compare the browser’s network log and response URL with a normal interactive session.

8. Performance, reliability, and cost

  • Reuse a browser process: launch Chromium once and create short-lived contexts per account or job. This avoids startup cost while keeping cookie jars isolated.
  • Bound waits: use navigation and selector timeouts; report the URL, status, and elapsed time when a capture fails.
  • Limit state: keep only the cookies required for the target origin and dispose of contexts after the job.
  • Control page size: choose the smallest viewport and screenshot region that answers the use case; full-page images consume more memory.
  • Retry carefully: retry transient navigation failures with a fresh context, but do not blindly retry authentication failures or expired sessions.
  • Protect secrets: redact cookie values from logs, traces, crash dumps, and CI artifacts.

Self-hosted browser automation costs the compute time and maintenance of a browser, driver, fonts, sandbox, and session store. A managed screenshot API can remove that setup when you only need an image or PDF.

9. Or skip the browser setup

ScreenshotNeo accepts a URL in one GET request and returns PNG, JPEG, WebP, or PDF. Its cookie and consent handling is useful when your goal is a clean page image rather than maintaining a Java browser: it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable.

A capture service can handle consent and overlays before rendering the final image.
A capture service can handle consent and overlays before rendering the final image.

Only clean shots are billed. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether it was billed.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/account -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/account"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/account' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
require('fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));

See the ScreenshotNeo API documentation for the 63 options: cookies and headers, custom user agents, waits, selectors, full-page and element capture, dark mode, device presets, retina scale, blocking rules, caching, signed links, async jobs, bulk capture, PDFs, and usage reporting. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

There is a free tier of 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

10. FAQ

Selenium requires the driver to be on a valid matching domain first. Playwright can add a cookie to a context before its first page navigation when you provide a URL or valid domain and path.

Applications may require additional cookies, a matching user agent or device, a CSRF token, or a server-side session that has expired. Compare all state from an authorized browser session.

Should I use Selenium or Playwright?

Both drive real browser engines. Playwright exposes context-scoped storage and convenient full-page and element screenshots; Selenium is widely available through WebDriver and makes the valid-domain prerequisite explicit.

Is HtmlUnit equivalent to Chrome?

No. HtmlUnit is a separate GUI-less Java implementation. Check JavaScript and layout compatibility before using it for pixel-sensitive captures.