ScreenshotNeo

BlogHow-to

How to Get the Default Value of a Puppeteer Dialog

Read a prompt’s prefilled text with Puppeteer’s `dialog.defaultValue()`. Learn how dialog types, async handling, errors, and screenshot workflows affect your code.

By the ScreenshotNeo team4 October 20266 min read

Use dialog.defaultValue() inside a handler for the page’s dialog event. It returns the initial text for a JavaScript prompt(); for alert, confirm, or beforeunload dialogs, it returns an empty string. Read the value before accepting or dismissing the dialog.

page.on('dialog', async dialog => {
  const initialText = dialog.defaultValue();
  console.log(initialText);
  await dialog.accept();
});

Puppeteer documents defaultValue() as returning the prompt’s default value, or an empty string when the dialog is not a prompt. See the Puppeteer Dialog.defaultValue() API reference and Dialog.accept().

1. How the dialog event and default value work

A page emits a dialog event when page JavaScript opens a browser dialog. The event handler receives a Puppeteer Dialog object. Its type() method identifies the kind of dialog, and defaultValue() reads the text supplied as the second argument to prompt(message, defaultValue).

const type = dialog.type();       // 'prompt', 'alert', 'confirm', or 'beforeunload'
const value = dialog.defaultValue();

The browser’s prompt(message, default) uses the supplied default as its initially populated response. Puppeteer exposes that value through the dialog object while the dialog is being handled. See the HTML Living Standard for the browser prompt behavior.

2. Complete runnable example

This example launches Chromium, creates a page that opens a prompt, captures its default text, accepts the prompt, and prints the submitted response. Install Puppeteer first with npm install puppeteer; then save the code as dialog-default.js and run node dialog-default.js.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });

  try {
    const page = await browser.newPage();

    page.on('dialog', async dialog => {
      try {
        console.log('Dialog type:', dialog.type());
        console.log('Prompt default:', dialog.defaultValue());
        await dialog.accept();
      } catch (error) {
        console.error('Could not handle dialog:', error);
      }
    });

    await page.setContent(`
      <button id="ask">Open prompt</button>
      <script>
        document.querySelector('#ask').addEventListener('click', () => {
          const answer = prompt('Your name?', 'Ada Lovelace');
          document.body.dataset.answer = answer ?? 'cancelled';
        });
      </script>
    `);

    await page.click('#ask');
    await page.waitForFunction(
      () => document.body.dataset.answer !== undefined
    );
    console.log('Page received:', await page.evaluate(
      () => document.body.dataset.answer
    ));
  } finally {
    await browser.close();
  }
})();

The handler calls accept() without an argument, so the prompt is accepted using its current default text. A prompt’s default can be an empty string, and page code can also supply no second argument; the returned value in those cases is still a string.

3. Read the value and choose how to resolve the dialog

Every JavaScript dialog must be resolved for the page to continue. Read its type and value first, then accept or dismiss it according to the test or automation task.

Goal Handler action Effect
Accept the prompt’s existing default await dialog.accept() Submits the current prompt text.
Accept with replacement text await dialog.accept('Grace Hopper') Submits the supplied text for a prompt. The text argument has no effect on other dialog types.
Cancel a prompt or reject a confirm await dialog.dismiss() Closes the dialog as cancelled or rejected.
Handle dialogs differently by kind Check dialog.type() before resolving Lets one listener support prompt, alert, confirm, and beforeunload.
page.on('dialog', async dialog => {
  const type = dialog.type();
  const defaultText = dialog.defaultValue();

  if (type === 'prompt') {
    console.log('Initial prompt text:', defaultText);
    await dialog.accept('Submitted value');
    return;
  }

  if (type === 'confirm') {
    await dialog.dismiss();
    return;
  }

  // Alerts and beforeunload do not have a prompt value.
  console.log(`Handling ${type}; default value: ${defaultText}`);
  await dialog.accept();
});

Use a single dialog handler for the page and make sure every path resolves the dialog. An unresolved dialog can leave an action such as click() waiting indefinitely.

4. Common mistakes and troubleshooting

Symptom Likely cause Fix
defaultValue() is empty The dialog is not a prompt, or the prompt was opened with an empty default. Log dialog.type(). Only prompt dialogs carry a prompt default; the method returns an empty string for other dialog types.
The click or navigation appears stuck The dialog event was not handled, or the handler did not call accept() or dismiss(). Register the listener before the action that triggers the dialog, and resolve every dialog path.
The page receives unexpected text The handler passed a replacement to accept(). Call accept() with no argument to use the current prompt default, or pass the intended replacement explicitly.
An error says the dialog is already handled or closed More than one handler or code path tried to resolve the same dialog. Centralize resolution in one listener and avoid calling accept() or dismiss() a second time.
No dialog event is observed The page action did not execute the code that opens a JavaScript dialog, or the listener was attached too late. Attach page.on('dialog', ...) before clicking or evaluating the triggering action; confirm the page actually calls alert(), confirm(), or prompt().
The prompt is cancelled instead of submitted The handler called dismiss(). Use accept() to submit. Use dismiss() only when cancellation is intended.

5. Timing, reliability, and test design

  • Subscribe before triggering: register the event listener before clicking a button or running page code that may open a dialog.
  • Always settle the dialog: await accept() or dismiss() in the handler. This makes the decision explicit and allows the page to proceed.
  • Keep the listener focused: capture or assert the default in the handler, then resolve promptly. Do not wait for page work that itself depends on the dialog closing.
  • Assert the type and value: tests should distinguish an empty prompt default from a non-prompt dialog, which also returns an empty string.
  • Clean up listeners when needed: if a page is reused across test cases, remove a one-off handler after the expected dialog so later dialogs are not processed by stale test logic.

This method does not require a network request or an external screenshot service. Its resource cost is the browser process and the page work your automation already performs. For reliable runs, close the browser in a finally block and handle errors from dialog resolution.

6. Or skip the browser setup

If your goal is to capture a page rather than inspect a prompt’s JavaScript default, ScreenshotNeo provides a website screenshot API and MCP server. A single GET request returns a screenshot or PDF, and its browser workflow handles consent banners before capture. The API parameter names used by other screenshot APIs also work. See the ScreenshotNeo API documentation.

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

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await require('node:fs/promises').writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie banners, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are never billed. Responses identify the page verdict and billing status in headers.
  • An MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf.
  • The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan.

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

7. FAQ

Does defaultValue() work for an alert?

It returns an empty string for an alert because alerts are not prompts and have no input default.

Can I read the value after accepting the dialog?

Read it in the dialog handler before resolving the dialog. Treat the dialog object as the event-time interface for inspecting and handling that dialog.

Does passing text to accept() change the original default?

No. It supplies text to submit for a prompt; it does not change the value returned by defaultValue().

Can Puppeteer retrieve a prompt default without handling the dialog?

Use the dialog event to obtain the dialog object and read its value. The handler should also accept or dismiss the dialog so page execution can continue.