keepcalculator

06 Numbers and Powers

Java Playwright Storage State for Authenticated Screenshots

Card No. 06·24638 · Updated · Standard formula, shown below

Yes. In Java Playwright, save an authenticated browser context’s storage state after logging in, then create a new context with that state and navigate to the protected page before taking a screenshot. This reuses supported browser storage such as cookies and local storage, but it does not automatically preserve every kind of session data or guarantee that the site will stay logged in.

How storage state works

Playwright’s storage state is a snapshot of browser data used to restore an authenticated session in another browser context. In Java, the main APIs are BrowserContext.storageState() to save it and Browser.newContext(new Browser.NewContextOptions().setStorageStatePath(path)) to load it.

A browser context is an isolated browser session. Saving state from one context and loading it into a fresh context is useful for repeatable tasks such as capturing a dashboard screenshot without submitting the login form on every run. It is also a common test setup: authenticate once in a setup step, then reuse the saved state for tests.

The state file can contain cookies and local-storage entries for origins that have been visited. Playwright can also include IndexedDB data when requested in versions that support the relevant option. Session storage is not included by the ordinary storage-state snapshot, and browser state such as open tabs, page history, or in-memory JavaScript variables is not restored.

Save state after logging in

First launch a browser, create a context, and complete a real login flow. Wait for a reliable indication that authentication succeeded, such as a user menu or a page heading that appears only after login. Then save the context state to a file.

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.nio.file.Paths;

public class SaveAuth {
  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();
      Page page = context.newPage();

      page.navigate("https://example.test/login");
      page.locator("#username").fill(System.getenv("TEST_USER"));
      page.locator("#password").fill(System.getenv("TEST_PASSWORD"));
      page.locator("button[type=submit]").click();
      page.locator("[data-testid=account-menu]").waitFor();

      context.storageState(new BrowserContext.StorageStateOptions()
          .setPath(Paths.get("playwright/.auth/state.json")));
      browser.close();
    }
  }
}

This is illustrative code: the URL, selectors, and success condition must match the application. In a real project, import BrowserType as well. Use a clear success check rather than a fixed sleep; network delays and application behavior vary.

Load the state and take a screenshot

Create a new context using the saved state, open a page, and navigate to the authenticated URL. The screenshot API can capture the visible viewport or the full page.

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.nio.file.Paths;

public class CapturePage {
  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()
              .setStorageStatePath(Paths.get("playwright/.auth/state.json")));
      Page page = context.newPage();
      page.navigate("https://example.test/account");
      page.locator("[data-testid=account-heading]").waitFor();
      page.screenshot(new Page.ScreenshotOptions()
          .setPath(Paths.get("account.png"))
          .setFullPage(true));
      browser.close();
    }
  }
}

In Java, the option type for creating a context is Browser.NewContextOptions. The path must point to the state file created in the first step. Both snippets assume the Playwright Java dependency and its browser installation are already configured.

  1. Authenticate and verify success in the first context.
  2. Write the storage state to a file in a controlled location.
  3. Start a new context with that file and visit the target page.
  4. Wait for a page-specific element or other reliable ready condition.
  5. Capture the viewport or set setFullPage(true) for a full-page image.

What storage state does not restore

A screenshot job can still land on a login page even when the state file loads correctly. The site may rely on session storage, a server-side session that has expired, a different hostname, or a login flow that requires a fresh challenge. Storage state transfers browser-side data; it does not extend the server’s session lifetime or bypass the application’s authentication rules.

Check that the saved state was created after login completed and that the destination uses the same scheme, hostname, and relevant origin. A cookie scoped to one host may not authenticate a sibling subdomain. If authentication depends on session storage, you need an application-appropriate setup that initializes that storage before the app runs; it is not supplied by the standard storage-state file.

Also, avoid assuming that a screenshot of a page proves the session was authenticated. The page might have redirected, rendered a public fallback, or displayed a cached shell. Assert an authenticated-only element or inspect the final URL before capturing.

Common problems and practical fixes

  • Redirected to login: Confirm that the login-success wait completed before saving, then regenerate the state. Check the final URL and whether the target shares the relevant origin.
  • State works once, then fails: Cookies can expire or be invalidated by logout, password changes, or server policy. Re-run the login setup when needed rather than treating the file as permanent.
  • Page is blank or incomplete: Wait for a meaningful locator, and account for app-specific loading. page.navigate() reaching a document load event does not necessarily mean a client-rendered page is ready.
  • Full-page image misses content: Some pages load content only while scrolling or use fixed and virtualized layouts. Trigger the page’s normal loading behavior and verify the captured image for that application.
  • File path errors: Use a stable path and ensure the process can read it. Java’s Paths.get avoids hard-coding platform-specific separators.

Screenshot options also affect the result. By default, the screenshot is of the current viewport. Set full-page capture when the entire document is needed; specify a path to save an image, and choose a file extension that matches the intended format. For consistent visual comparisons, keep browser, viewport, device scale factor, fonts, and page state consistent between runs.

Protect the authentication file

Storage-state files are credentials in practice: a person who can use a still-valid session cookie may be able to access the account without knowing its password. Do not commit them to source control, publish them as build artifacts, or include them in screenshots or logs. Store them in a restricted location, use a dedicated test account with only the access required, and delete or refresh the file when it is no longer needed.

For a repository, add the authentication-state directory to the ignore rules, while ensuring the setup process creates it when required. In CI, provide credentials through the environment or an approved secrets mechanism, generate the state during the job, and limit its lifetime and access. These precautions protect the session; they do not replace the application’s normal access controls.

Frequently Asked Questions

Can Java Playwright take screenshots without logging in each time?
Yes. Save state after a successful login, then load it into a new browser context. This avoids repeating the login flow while the saved session remains valid.

Does Playwright storage state include session storage?
No, the ordinary storage-state snapshot does not preserve session storage. It principally covers cookies and local storage, with optional IndexedDB support in applicable versions.

Should I reuse the same page or create a new context?
A new context loaded from the state file gives a clean, isolated session and is a good default for repeatable captures. Reusing a page is possible, but it does not test that the saved state can restore authentication.

How can I capture the whole authenticated page?
Use page.screenshot(new Page.ScreenshotOptions().setPath(path).setFullPage(true)). Wait for the page’s content to be ready first, especially when it loads content dynamically.

Why does a saved state stop working?
The session may expire or be revoked, the site may require additional browser-side state, or the target may use a different origin. Re-authenticate and save a fresh state, then verify the page is genuinely authenticated before capture.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →