ScreenshotNeo

BlogHow-to

Set a custom user agent for website screenshots in Playwright Java

Set a custom user agent on a Playwright Java browser context, then capture a viewport or full-page screenshot with runnable code and troubleshooting tips.

By the ScreenshotNeo team4 October 20266 min read

Set the user agent on a Playwright Java BrowserContext with Browser.NewContextOptions.setUserAgent(...). Then create the page from that context, navigate to the site, and call Page.screenshot(...). The user agent belongs to the browser session configuration; it is not a screenshot option.

1. Add Playwright Java and install a browser

Use the Playwright Java dependency in your project and install the browser binaries for the version you use. For Maven, add the dependency below, replacing the version with the version selected for your project:

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>YOUR_PLAYWRIGHT_VERSION</version>
</dependency>

Install the matching browser binaries with the Playwright CLI for Java. Browser launch is headless by default. See the Playwright Java introduction for setup instructions. Keep the library and browser installation aligned, especially in CI.

2. Set the user agent and save a screenshot

This complete example creates Chromium, applies a custom user agent to a context, opens a page in that context, navigates, and writes a viewport screenshot to screenshot.png. Replace the sample string with the exact user-agent value your test needs.

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class ScreenshotWithUserAgent {
  public static void main(String[] args) {
    String userAgent = "Example custom user agent";

    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      try {
        BrowserContext context = browser.newContext(
            new Browser.NewContextOptions().setUserAgent(userAgent));
        try {
          Page page = context.newPage();
          page.navigate("https://example.com");
          page.screenshot(new Page.ScreenshotOptions()
              .setPath(Paths.get("screenshot.png")));
        } finally {
          context.close();
        }
      } finally {
        browser.close();
      }
    }
  }
}

The try/finally blocks close the context before the browser, including when navigation or capture fails. A directly created context should be closed explicitly. The official Browser API describes setUserAgent as the user agent to use in that context.

3. Choose viewport or full-page capture

By default, the screenshot covers the current viewport. To capture the full scrollable page, enable setFullPage(true):

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("full-page.png"))
    .setFullPage(true));

Use the format and capture options supported by the Playwright version in your project. Screenshot options control output and capture behavior; they do not change the user agent. See the Page screenshot API for options such as path, full-page capture, image format, and quality. Consult the release notes for your installed version if an option is missing.

4. Understand context scope and isolation

A browser context is an isolated browser session and owns its pages. The configured agent applies to pages created from that context. If two captures need different user agents, create a separate context for each configuration rather than trying to change the screenshot call.

Popups opened by a page belong to the parent page’s context, so they use that session configuration too. Context isolation also helps keep cookies and other session state separate between captures. The BrowserContext API documents the relationship between contexts and their pages.

5. Pick the right user-agent string

There is no universal custom user-agent value for screenshot work. Use the exact string required by the behavior you are testing, such as a string supplied by your application test case. A user-agent override changes what the site receives for that browser session; it does not by itself reproduce every browser, device, or operating-system characteristic.

Playwright’s emulation guide says the user agent is normally included in a device profile, but can be overridden with the userAgent property when needed. Avoid selecting an arbitrary string just to make a site render differently: that makes the test harder to interpret and does not guarantee that the rest of the environment matches.

6. Troubleshoot common problems

Symptom Likely cause Fix
The site still behaves as if the old user agent is in use. The page was created from a different context, or the option was applied after the page was created. Set setUserAgent when calling browser.newContext, then create the page with context.newPage().
The screenshot API has no user-agent setter. The user agent is configured at context creation, not in Page.ScreenshotOptions. Move the setting to Browser.NewContextOptions. Keep screenshot options for capture and output settings.
The capture has the wrong dimensions or cuts off page content. A normal screenshot is viewport-only, or the viewport was not configured as expected. Use setFullPage(true) for the full scrollable document. Configure the context viewport if the test requires specific viewport dimensions.
Browser startup reports missing executables. The Playwright library is present, but its browser binaries are not installed or do not match the library version. Run the Java Playwright browser installation command for the project’s installed version, following the official setup guide.
A later capture inherits unexpected cookies or session state. The page reused a context that was intended to be isolated. Create a fresh context for the independent capture and close it when done.
A screenshot file is absent after an exception. Navigation or capture failed before the screenshot write completed, or the process cannot write to the destination. Check the exception, destination directory, and process permissions. Use an explicit absolute path when diagnosing path confusion.

7. Reliability, speed, and cost considerations

For repeated captures, reuse the Playwright process and browser where appropriate, while using contexts to isolate sessions and user-agent settings. Close each context after its work and close the browser when the run ends. This avoids leaking browser resources while preserving the configuration boundary between sessions.

Page load time, site behavior, and screenshot dimensions can vary with network conditions and page content. Full-page captures may involve substantially more content than viewport captures, including content below the fold. For stable automation, use a deterministic target and the appropriate navigation or page-readiness condition before capture; do not assume that changing the user agent makes a slow page load faster.

Playwright is browser automation software; this workflow has no ScreenshotNeo API charge. Your infrastructure still needs to run Java and a browser. If you need a hosted screenshot API instead, ScreenshotNeo pricing is Free for 1,000 shots per month, Starter $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000; annual billing gives two months free, and every feature is on every plan.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server by Yorker Media. One GET request can return a screenshot or PDF. Its API also accepts the parameter names used by other screenshot APIs, which can make a switch straightforward. Read the ScreenshotNeo API documentation for request details.

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

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

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, failed loads, and cache hits are not billed. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000.

Sign up for 1,000 free screenshots a month with no card.

Frequently asked questions

Can I set a different user agent for each page?

Use a different browser context for each user-agent configuration. A page uses the settings of the context that created it.

Does setting the user agent change the screenshot file?

It can change the page the server returns or how client code responds, which can change the rendered image. The screenshot method itself does not set the user agent.

Can I capture a popup with the configured user agent?

Yes. A popup opened by a page belongs to its parent page’s context and uses that context’s configuration.

Where can I verify the exact Java method names?

Use the Playwright Java Browser API for NewContextOptions.setUserAgent and the Page API for screenshot options; these references match the Java binding.