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

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 website in a particular visitor state, first open the site in a browser context for the correct domain, add or restore the required cookie state, then reload or navigate to the page and verify the expected state before taking the screenshot. In Selenium, use driver.manage().addCookie(...); in Playwright Java, add cookies to a BrowserContext. A cookie alone is not always enough to sign in: the application may also depend on local storage, IndexedDB, or session storage.

Choose Selenium or Playwright for the capture

Use Selenium if your project already relies on WebDriver and you want its standard cookie controls and driver- or element-level screenshots. Use Playwright Java if isolated browser contexts, reusable storage state, or explicit viewport, full-page, and element screenshot options suit your test better. Both approaches can set cookies before capture. The official API documentation describes their behavior, but does not establish that a particular website will accept an injected cookie or prove one tool is faster.

The sequence is the same whichever library you choose: use an authorized test account and a site you may access; establish the matching browser context and domain; add or restore state; load or refresh the target page; wait for an application-specific indication that the intended visitor state rendered; then capture and protect any saved authentication data.

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

Set a cookie and capture a page with Selenium Java

WebDriver adds a cookie to the cookie store for the active document in the current browsing context. Visit a page on the cookie’s domain before calling addCookie. The cookie’s domain and path must be appropriate for the target, and its value must be a legitimate test value supplied by your application or test setup—not a guessed production session token.

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Example: add a test preference cookie

This example uses a host-matching test cookie, refreshes the page so the application can read it, waits for an app-specific visible state, and saves a viewport screenshot. Replace the URL, cookie, and selector with values for an authorized test environment. The API pattern is documented by Selenium; the example is not a claim that it has been run against a particular website.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.By;
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) throws IOException {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.test/"); // Visit the cookie's domain first

            Cookie preference = new Cookie.Builder("preference", "compact")
                    .domain("example.test")
                    .path("/")
                    .build();
            driver.manage().addCookie(preference);
            driver.navigate().refresh();

            // Replace this with a selector that proves the intended state rendered.
            new WebDriverWait(driver, Duration.ofSeconds(10))
                    .until(ExpectedConditions.visibilityOfElementLocated(
                            By.cssSelector("[data-test='compact-layout']")));

            File image = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE);
            Files.copy(image.toPath(), Path.of("cookie-state.png"));
        } finally {
            driver.quit();
        }
    }
}

The selector is deliberately application-specific. A successful addCookie call only means the browser accepted the cookie operation; it does not prove the site recognized the value or rendered the desired state. Wait for a meaningful element, title, or other test assertion before saving the image. If the application reads the cookie only during initial navigation, refresh or navigate to the target after adding it.

Set only the cookie attributes your test needs

Selenium also supports the simple form new Cookie("key", "value") after visiting a page on the matching site. A builder is useful when the application requires explicit scope or expiry behavior. Set the domain and path to match the site, and use the appropriate expiry, Secure, HttpOnly, and SameSite settings when your test depends on them. Do not broaden a cookie’s domain or make assumptions about what a production application accepts.

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

Inspect browser state with driver.manage().getCookieNamed("preference") or driver.manage().getCookies(). Clean up test state with the cookie deletion methods, such as deleting one named cookie or deleting all cookies, where that is appropriate for your test. A screenshot of an authenticated page should be treated separately from the browser state: capturing an image does not make the underlying session safe to share.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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 a driver or a specific element

Selenium’s TakesScreenshot interface supports output as a file or Base64, and can be used with a driver or an element that supports screenshots. The example above captures the current driver viewport to a file. If the subject is one component, cast the target element to TakesScreenshot and request the same output type from it. Choose the capture target intentionally; a driver screenshot is not automatically a full-page image.

Use cookies and screenshots with Playwright Java

Playwright attaches cookies to a BrowserContext, rather than adding them through the page. A context can be isolated for a test run. Add a cookie using a URL or a domain-and-path combination, then open or reload the page and wait for the intended UI before taking the screenshot.

Example: add a cookie and save a full-page screenshot

Use a real test fixture for the cookie and an application-specific assertion. This example shows the API sequence; it does not imply a particular site will accept the cookie.

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.
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.Cookie;
import com.microsoft.playwright.options.LoadState;
import com.microsoft.playwright.options.ScreenshotOptions;

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();

            Cookie preference = new Cookie("preference", "compact")
                    .setUrl("https://example.test/");
            context.addCookies(List.of(preference));

            Page page = context.newPage();
            page.navigate("https://example.test/");
            page.locator("[data-test='compact-layout']").waitFor();
            page.screenshot(new Page.ScreenshotOptions()
                    .setPath(Paths.get("cookie-state.png"))
                    .setFullPage(true));

            browser.close();
        }
    }
}

Use the cookie constructor and scope that fit the Playwright Java version in your project; the API accepts cookie data scoped by URL or by domain and path. The example uses a URL scope to make the intended origin explicit. Playwright screenshot options also support element capture and returning screenshot bytes rather than writing directly to a path. Use a page capture for the viewport, full-page capture for the full scrollable page, or an element locator’s screenshot for a component.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

Reuse authenticated state between runs

For repeated authenticated runs, Playwright’s storage-state workflow can save and load common persisted browser state, including cookies and local storage; the authentication guide also covers IndexedDB state. This is often more maintainable than manually constructing an opaque session cookie. Follow the application’s supported login flow to create the state file, then initialize a context from it for later captures.

Storage state is sensitive. It may contain cookies or headers that allow someone to impersonate the account. Keep it out of source control, restrict file access, use a dedicated test account, and rotate or invalidate the credentials when needed. Session storage is not covered by the documented storage-state persistence flow; applications relying on it need separate initialization for the relevant page or context.

Make the captured image match the intended result

  • Confirm scope: the cookie must belong to the site and path being visited. Browser APIs cannot use a cookie scoped to an unrelated host as if it were valid for the target.
  • Confirm timing: add state before the navigation that needs it, or reload after insertion if the page has already loaded.
  • Wait for rendered evidence: wait for the signed-in name, selected preference, or a stable test selector instead of assuming navigation completion means the UI is ready.
  • Select capture extent: choose viewport, full page, or a single element according to the question the screenshot needs to answer.
  • Keep state isolated: use a clean browser context or profile for each independent test so cookies from one run do not silently affect another.

Cookie acceptance and screenshot rendering are separate concerns. The APIs let you establish browser state and capture what is rendered; they do not guarantee the target site’s authentication rules, dynamic content, or layout behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot cookie-based captures

The browser rejects the cookie

In Selenium, check that the current page is on the cookie’s domain before calling addCookie. Then review domain and path scope, expiry, and any security attributes required by the application. In Playwright, check that the supplied URL or domain/path matches the intended site. Do not try to work around a site’s access controls; use its documented test login or authorized test fixture.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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

The screenshot still looks logged out

A cookie may be expired, scoped incorrectly, or only one part of the application’s state. The application may rely on local storage, IndexedDB, or session storage in addition to cookies. Check the application’s authentication design, verify the cookie in the active context, and wait for a visible authenticated-state indicator. For Playwright repeat runs, consider saved storage state for supported persisted data; handle session storage separately when required.

The screenshot is blank, incomplete, or the wrong size

Check that the navigation succeeded and that the page reached the expected state before capture. A viewport screenshot, a full-page screenshot, and an element screenshot show different areas; select the one required. For dynamic pages, wait for a stable selector rather than relying only on a fixed delay. If full-page capture is needed, use Playwright’s full-page option or capture a suitably scoped element, and verify the resulting dimensions in the test.

State works locally but cannot be shared safely

Do not commit a Playwright state file or a file containing session cookies. The data can enable account impersonation. Keep credentials in a protected test environment, limit access, and use non-production accounts and data wherever possible.

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

You need WebP output

Playwright Java release notes document WebP screenshot output. The format can be inferred from a .webp output path or set explicitly in screenshot options in versions that support that option. Check the release notes for your installed Playwright Java version before relying on a particular format option.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

Or skip the browser setup

If you need an image or PDF from a URL without managing a Selenium or Playwright session, ScreenshotNeo provides a website screenshot API and MCP server. Its API returns PNG, JPEG, WebP, or PDF; the one-call example below saves a WebP screenshot. See the ScreenshotNeo API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Can I use the same cookie in Selenium and Playwright?

The cookie data may be portable if its value, domain, path, and attributes fit the target application, but each library must add it to its own browser context.

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

Does setting a cookie automatically log me in?

No. The application must accept that cookie, and its authentication may depend on additional state or checks.

Can I capture a WebP screenshot with Playwright Java?

Yes, according to the Playwright Java release notes; support can depend on the version, and the format may be selected by a .webp path or an explicit option.

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.