×
☰ See All Chapters

Handling JavaScript prompt in Puppeteer

Puppeteer provides a “Dialog” class for Confirm popup. When a Confirm popup is displayed, we have to obtain Dialog object of Confirm popup to access it. To access the Confirm popup displayed on the screen as an instance of the “Dialog” class, we have to attach the dialog event to page.

async function handlePrompt( page: Page ): Promise<void> {

    const element = await page.$( "#prompt" );

    element.click();

    page.on( 'dialog', async dialog => {

        console.log( dialog.type() );

        console.log( dialog.message() );

        await dialog.accept( "Hello" );

    } );

}

Dialog class provides the below list of methods to handle alert:

Method

Description

accept(promptText: string): Promise<void>

Pass the text to enter in prompt to this accept method. Once prompt text is entered, accepts and closes the dialog

defaultValue(): string

Returns default prompt value

dismiss(): Promise<void>

Dismiss the prompt.

message(): string

Returns the message displayed in the dialog.

type(): DialogType

The dialog type. Dialog's type, can be one of ‘alert’, ‘beforeunload’, ‘confirm’ or ‘prompt’

You can write the script and test these using our Test Page

handling-javascript-prompt-in-puppeteer-0
 

Puppeteer JavaScript prompt Example

import { launch, Page } from 'puppeteer';

example();

async function example() {

    const browser = await launch( { headless: false } );

    const page = await browser.newPage();

    await page.setViewport( { width: 1366, height: 768 } );

          await page.goto( 'https://www.tools4testing.com/contents/puppeteer/testpages/handling-javascript-pop-ups-testpage' );

    await handleAlert( page );

    await browser.close();

}

 

async function handlePrompt( page: Page ): Promise<void> {

    const element = await page.$( "#prompt" );

    element.click();

    page.on( 'dialog', async dialog => {

        console.log( dialog.type() );

        console.log( dialog.message() );

        await dialog.accept( "Hello" );

    } );

}

Click here to learn to execute puppeteer example using typescript

 


All Chapters
Author