October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Set a Custom User Agent for Website Screenshots in Playwright Java

Set the user agent on a Playwright Java BrowserContext before creating a page, then capture a viewport or full-page screenshot.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set the user agent on a Playwright Java BrowserContext, not on the screenshot call. Create a page from that context, navigate to the site, and capture it with Page.screenshot(...). The user-agent string is up to your test; Playwright does not prescribe a universal value.

Set the user agent on the browser context

Use Browser.NewContextOptions.setUserAgent(...) when creating the context. Pages created by that context use its configuration, so set the value before opening the page or navigating.

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

public class ScreenshotWithUserAgent {
  public static void main(String[] args) {
    String userAgent = "Example custom user agent"; // Replace with the exact value your test requires.

    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      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();
        browser.close();
      }
    }
  }
}

Replace Example custom user agent with the exact string your test needs and change https://example.com to the target URL. The example launches Chromium headlessly by default, navigates, and writes a viewport screenshot to screenshot.png. A custom context created directly from the browser should be closed before the browser.

Choose the user-agent string for the test

The right value depends on what you are testing: for example, how a site responds to a particular browser or client identity. Use the exact string required by that scenario; there is no universally correct custom user agent. Playwright’s emulation guide notes that the user agent is ordinarily included with device emulation, but can be overridden with the userAgent property when needed.

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

This setting changes the user-agent value sent by pages in the configured context. It does not, by itself, configure other browser or device characteristics. If a test requires a different context configuration, create a separate context for it rather than trying to change screenshot options.

Choose viewport or full-page capture

The user-agent setting and screenshot settings serve separate purposes: configure the former on context creation, and use Page.screenshot(...) for the image output.

  • Viewport screenshot: use new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")), as in the runnable example.
  • Full-page screenshot: add .setFullPage(true) to the screenshot options to capture the page’s full scrollable area.

For example, replace the screenshot call with:

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

The Java screenshot API also exposes controls for output format, quality, scale, masking, and related capture behavior. Check the API reference for your installed Playwright version for the exact options available; screenshot capabilities can change between versions.

Or skip the browser setup

If you need an image from a URL without managing a Playwright browser context, ScreenshotNeo provides a website screenshot API and MCP server. Its URL-based endpoint returns an image or PDF, and accepts user-agent parameters used by other screenshot APIs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://example.com 
  -o shot.webp

See the ScreenshotNeo API documentation for authentication and request options. Before capture, it accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots a 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.

Troubleshoot common problems

The page still appears to use a different user agent

Confirm that setUserAgent(userAgent) is on the options passed to browser.newContext(...), and that the page was created from that context. A page created elsewhere will not inherit this context’s setting. If you need a different value, create a context with that value before creating its page.

The screenshot is only the visible portion of the page

That is the default viewport capture. Add .setFullPage(true) to Page.ScreenshotOptions when you need the full scrollable page.

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

The screenshot option does not compile

Check the Java API reference and release notes for the Playwright version used by your project. Screenshot options evolve, so an option shown for another version may not be available in yours. The basic user-agent setup uses the context’s setUserAgent; screenshot output options belong to Page.ScreenshotOptions.

The target page has not finished rendering when captured

page.navigate(...) completes navigation according to its configured load behavior, but a site may continue rendering content afterward. If the screenshot misses content, wait for the page state or element your test depends on before calling screenshot; choose a condition tied to the content rather than adding an arbitrary delay where possible.

Resources remain open after the capture

Close a directly created context and then its browser, including when an exception occurs. The nested try/finally in the example ensures that cleanup order.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability and version notes

Browser launches are headless by default in Playwright Java. For predictable results, use the same Playwright version, browser engine, viewport, and user-agent string across runs, and close the context after capture. If an API option behaves differently or is unavailable, consult documentation and release notes for the version your project actually uses. The basic context-based user-agent workflow does not depend on version-specific WebP screenshot support.

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.

Frequently Asked Questions

Does changing the user agent also emulate a device?

No. The context option overrides the user-agent value; it does not by itself configure the other characteristics of a device.

Can a popup use the configured user agent?

A popup opened by a page belongs to its parent page’s browser context, so it uses that context’s settings.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.