playwright/docs/src/api/class-dialog.md
Dmitry Gozman 53ed35ef96
feat(dialogs): auto-dismiss dialogs when there are no listeners (#5269)
This makes dialogs disappear and prevents stalling.

Pros:
- No need to worry about dialogs for most users.
- Those that wait for a specific dialog still get to control it.

Cons:
- Those who use Playwright to show interactive browser will have
  to add an empty 'dialog' handler to prevent auto-dismiss.
  We do this in cli.
2021-02-03 10:34:45 -08:00

2.4 KiB

class: Dialog

[Dialog] objects are dispatched by page via the [event: Page.dialog] event.

An example of using Dialog class:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  page.on('dialog', async dialog => {
    console.log(dialog.message());
    await dialog.dismiss();
    await browser.close();
  });
  page.evaluate(() => alert('1'));
})();
import asyncio
from playwright.async_api import async_playwright

async def handle_dialog(dialog):
    print(dialog.message)
    await dialog.dismiss()

async def run(playwright):
    chromium = playwright.chromium
    browser = await chromium.launch()
    page = await browser.new_page()
    page.on("dialog", handle_dialog)
    page.evaluate("alert('1')")
    await browser.close()

async def main():
    async with async_playwright() as playwright:
        await run(playwright)
asyncio.run(main())
from playwright.sync_api import sync_playwright

def handle_dialog(dialog):
    print(dialog.message)
    dialog.dismiss()

def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch()
    page = browser.new_page()
    page.on("dialog", handle_dialog)
    page.evaluate("alert('1')")
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

:::note Dialogs are dismissed automatically, unless there is a [event: Page.dialog] listener. When listener is present, it must either [method: Dialog.accept] or [method: Dialog.dismiss] the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish. :::

async method: Dialog.accept

Returns when the dialog has been accepted.

param: Dialog.accept.promptText

  • promptText <[string]>

A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt. Optional.

method: Dialog.defaultValue

  • returns: <[string]>

If dialog is prompt, returns default prompt value. Otherwise, returns empty string.

async method: Dialog.dismiss

Returns when the dialog has been dismissed.

method: Dialog.message

  • returns: <[string]>

A message displayed in the dialog.

method: Dialog.type

  • returns: <[string]>

Returns dialog's type, can be one of alert, beforeunload, confirm or prompt.