DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › browser automation

How to Take a Screenshot of a Page with a Browser Alert in Playwright

By Freedom251 Team · · 4 min read

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

Handle the JavaScript dialog before taking the screenshot. Register a dialog listener before the action that triggers the alert, then accept or dismiss it. Playwright’s page screenshot captures the page; its documentation does not say that it captures the browser-native alert while it is open. If the alert’s text needs to appear in the image, read it from the dialog and render it into the page first.

Handle the alert before taking the screenshot

Playwright exposes JavaScript alert, confirm, prompt, and beforeunload dialogs through the dialog event. A dialog blocks page interaction until handled. With no page- or context-level dialog listener, Playwright automatically dismisses it; once you install a listener, that listener must accept or dismiss the dialog or the triggering action can stall. See the Playwright dialogs guide.

As an Amazon Associate I earn from qualifying purchases.

Register the listener before clicking the control that opens the alert. This example saves the message, accepts the dialog, adds the message to the document, and captures the full page:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const alertMessage = new Promise(resolve => {
  page.once('dialog', async dialog => {
    resolve(dialog.message());
    await dialog.accept();
  });
});

await page.getByRole('button', { name: 'Show alert' }).click();
const message = await alertMessage;

// Native browser alert chrome is not documented as part of page.screenshot().
// Render the message into the page if it must appear in the image.
await page.evaluate(text => {
  const note = document.createElement('pre');
  note.id = 'captured-alert';
  note.textContent = `Alert: ${text}`;
  document.body.append(note);
}, message);

await page.screenshot({ path: 'page-with-alert-message.png', fullPage: true });

The example uses Playwright’s documented dialog and page-screenshot APIs, but this particular sequence has not been independently tested here. The Page API documents page.screenshot() and options such as path and fullPage.

Choose accept or dismiss to match the test

Accepting or dismissing a dialog can change what the page does next. Choose the response that matches the behavior you are testing, rather than treating dialog handling as a screenshot-only detail. For an alert with no meaningful choice, accepting it is usually the straightforward way to let the scenario continue. For a confirmation dialog, use the response the test is intended to verify.

To dismiss instead, replace await dialog.accept(); with await dialog.dismiss();. For a prompt, pass a value to accept() if the scenario requires input—for example, await dialog.accept('test value');. Playwright documents these dialog operations in its Dialogs guide.

Use a context-level listener when the policy applies to multiple pages

A page-level listener such as page.once('dialog', ...) is useful when handling belongs to one test step. If the same policy should apply to pages in a browser context, use the documented context-level event:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
context.on('dialog', async dialog => {
  console.log(dialog.message());
  await dialog.accept();
});

Do not only log the message: a registered listener must settle the dialog by accepting or dismissing it.

Make the screenshot show the right thing

Capture the page after the dialog closes

Accept or dismiss the dialog, then call page.screenshot(). Add fullPage: true when the image should include the full scrollable document rather than only the current viewport. The screenshot API also provides options such as clipping, masking, scale, and output type; these tailor the page image but do not replace dialog handling. Consult the Page API for the current options.

Include the alert text as page content

Use dialog.message() in the event handler, then insert the returned string into the page or another test artifact before capturing. The example above appends a <pre> element and sets its textContent, so the message is treated as text rather than HTML. This is a practical workaround based on the documented dialog and screenshot APIs—not a guarantee that Playwright captures the native alert itself.

Keep a debugging record of the interaction

If the goal is to inspect a test’s sequence rather than create a single image as evidence, Playwright tracing may help: its trace viewer can display recorded screenshots and action snapshots. See the Trace viewer documentation.

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

Troubleshoot a stalled click or missing alert text

  • The click or next page action appears stuck: Check whether a dialog listener is installed and whether every dialog it receives is accepted or dismissed. A handler that only logs can leave the dialog blocking the page.
  • The listener never seems to run: Attach it before the click or other action that triggers the dialog. A one-time listener is consumed by the next dialog event on that page.
  • The screenshot has no alert: The documented page screenshot operation does not promise to include native browser alert chrome. Capture the message with dialog.message() and render it into page content if it must be visible in the image.
  • The page behaves differently after handling the dialog: Confirm that the test uses the intended accept or dismiss response; that response is part of the scenario and may affect subsequent page behavior.
  • The image cuts off lower content: Use fullPage: true to capture the full scrollable page instead of just the viewport.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For a URL-based screenshot without setting up a Playwright browser, ScreenshotNeo provides a screenshot API. Its one-call GET endpoint returns an image or PDF, but it does not document a way to control a Playwright-triggered JavaScript dialog or reproduce that dialog in the screenshot.

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

See the ScreenshotNeo API documentation for request options. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, with the response identifying the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

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

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.

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

browser automationJavaScriptPlaywrightscreenshotsweb testing

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.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.