Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober 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 PC×
Skip to content
World desk5 min

Use Playwright in Java to Screenshot a Page in Dark Mode

Use Playwright Java’s ColorScheme.DARK setting to request a dark-mode page, then save a viewport, full-page, or locator screenshot.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set Playwright’s color scheme to dark before navigating, then capture the page with Page.screenshot. This emulates the prefers-color-scheme: dark media feature; the site must support that preference for its design to appear dark.

Capture a full page in dark mode

Configure the browser context with ColorScheme.DARK before creating the page. Navigating after that lets page scripts observe the intended preference during initialization.

As an Amazon Associate I earn from qualifying purchases.

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

public class DarkScreenshot {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      BrowserContext context = browser.newContext(
          new Browser.NewContextOptions().setColorScheme(ColorScheme.DARK));
      try {
        Page page = context.newPage();
        page.navigate("https://example.com");
        page.screenshot(new Page.ScreenshotOptions()
            .setPath(Paths.get("dark-page.png"))
            .setFullPage(true));
      } finally {
        context.close();
        browser.close();
      }
    }
  }
}

Replace https://example.com with the page you want to capture. The screenshot is written to dark-page.png in the process’s working directory. Playwright Java’s installation documentation says browsers run headless by default, so this does not require a visible browser window: Playwright Java installation.

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

Install Playwright Java and its browser

Add the Playwright Java dependency using the installation instructions for your build system, then install the browser binaries required by your project. The Java installation guide lists Java 8 or higher and platform requirements; check it for current setup details because system requirements can change: Installation.

The example launches Chromium. If you use a different browser, launch the corresponding Playwright browser type and ensure its browser binary is installed.

Choose when to set dark preference

Set it for the whole context

Browser.NewContextOptions.setColorScheme(ColorScheme.DARK) applies the preference to pages created in that context. This is the clearest choice for a capture job that should consistently use dark preference.

Change an existing page

If the page already exists, emulate the media feature before taking the screenshot:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
page.emulateMedia(new Page.EmulateMediaOptions()
    .setColorScheme(ColorScheme.DARK));

For page creation with options, Playwright also provides page-level options such as Browser.NewPageOptions.setColorScheme(ColorScheme.DARK). Context configuration is preferable when you want a consistent setting for the context. The documented supported schemes are light and dark: Emulation.

Choose viewport or full-page capture

Without setFullPage(true), the screenshot covers the current viewport. Add that option to capture the full document height, as in the complete example above. Full-page capture can take longer and produce a taller image, especially on long pages.

For a minimal viewport screenshot, omit the full-page option:

Page page = context.newPage();
page.navigate("https://example.com");
page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("dark-page.png")));

When the page loads content as it scrolls, a full-page screenshot does not by itself guarantee every lazy-loaded image has appeared; check the resulting image if the site depends on scroll-triggered content.

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

Capture one element instead of the page

Use a locator when you want a particular element, such as a chart or card, rather than the whole page:

page.locator(".report-card").screenshot(
    new Locator.ScreenshotOptions()
        .setPath(Paths.get("report-card.png")));

Replace .report-card with a selector matching the element. Locator screenshots scroll the element into view and perform actionability checks. The Java API marks the older ElementHandle screenshot approach as discouraged; use Locator.screenshot for this case: Locator API and ElementHandle API.

Verify the preference and understand what it means

You can check whether the browser reports dark preference from page JavaScript:

Boolean prefersDark = (Boolean) page.evaluate(
    "() => matchMedia('(prefers-color-scheme: dark)').matches");
System.out.println("Dark preference: " + prefersDark);

A true result confirms that the media preference is emulated. It does not confirm that the site has a dark theme or that its colors rendered as intended. A page may ignore prefers-color-scheme or use a separate in-page theme control.

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

Set image format and resolution

The screenshot API supports PNG, JPEG, and WebP options, subject to the Playwright version installed in your project. PNG is a practical default for sharp UI text; choose another format when its file-size or image characteristics suit your use. Check the Java API for the exact format option supported by your version: Page API.

Screenshot scale controls output resolution. CSS scale produces one output pixel per CSS pixel; device scale uses device pixels and can create larger, high-DPI output. Select the scale option supported by your installed version when configuring Page.ScreenshotOptions. Consult the Page API and the release notes for version-specific details: Page API · Java release notes.

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

Close browser resources safely

The example closes the context before the browser in a finally block. Contexts isolate session state, and closing a directly created context before the browser helps flush its resources. Use try/finally or equivalent cleanup if you adapt the example to handle multiple pages or errors: BrowserContext API.

Troubleshooting

The screenshot is still light

  • Confirm the context or page was set to ColorScheme.DARK before capture.
  • Check matchMedia('(prefers-color-scheme: dark)').matches. If it is true, Playwright is advertising dark preference; the site may not implement a dark theme or may require its own theme control.
  • For a page changed after creation, call emulateMedia before the screenshot and allow the page to update.

The screenshot file is missing

  • Use a writable path and remember that a relative path such as dark-page.png is resolved from the Java process’s working directory.
  • Check that navigation and screenshot calls complete without an exception, and that the process reaches its cleanup block.

Browser launch fails

  • Install the browser binaries required by your Playwright Java setup, and check the installation guide for the operating system’s current requirements.
  • Confirm the Java runtime and Playwright dependency are compatible with the project’s setup instructions.

An element screenshot fails or is incomplete

  • Check that the locator matches the intended element and that the element can become actionable.
  • If the element depends on asynchronous page content, wait for the relevant content or selector before capturing.

Or skip the browser setup

ScreenshotNeo is a screenshot API and MCP server. It returns a screenshot or PDF from one GET request; its clean-shot steps can accept cookie or consent banners and remove known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, and response headers identify the page verdict and billing status. AI agents can use its MCP tools, including take_screenshot, get_page_info, and capture_pdf. It does not require you to configure Playwright in your own app for this request.

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.

For a basic capture, call the API with your access key and target URL. See the ScreenshotNeo API documentation for request options and response behavior.

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

The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does setting dark mode change a site’s own theme toggle?

No. It emulates the browser’s prefers-color-scheme preference; a site’s separate theme control may need to be set independently.

Can I capture only the visible browser viewport?

Yes. Use Page.screenshot without setting setFullPage(true).

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

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. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.