How can I handle JavaScript dialogs (e.g., confirm, prompt) with Puppeteer?
Alex K
alex k profile pic

Handling JavaScript dialogs (such as confirm and prompt dialogs) in Puppeteer involves intercepting and responding to the dialog events. Here's a detailed explanation of how to handle JavaScript dialogs using Puppeteer: 1. Intercepting dialog events:

1
2
3
4
5

   page.on('dialog', async (dialog) => {
     // Handle the dialog here
   });
   

Register an event listener for thedialog event on thepage object. This event is triggered when a dialog appears on the page. 2. Handling confirm dialogs: Inside the event listener, you can check the type of dialog usingdialog.type() and handle the confirm dialog accordingly:

1
2
3
4
5
6
7
8
9

   page.on('dialog', async (dialog) => {
     if (dialog.type() === 'confirm') {
       console.log('Confirm message:', dialog.message());
       await dialog.accept(); // Accept the confirm dialog
       // Or use dialog.dismiss() to dismiss the confirm dialog
     }
   });
   

When thedialog.type() returns'confirm', it means a confirm dialog has appeared. You can retrieve the message usingdialog.message(). In this example, the confirm message is logged to the console, and then theaccept() method is called to accept the dialog. Alternatively, you can usedialog.dismiss() to dismiss the dialog. 3. Handling prompt dialogs: Similarly, you can handle prompt dialogs by checking the dialog type and responding accordingly:

1
2
3
4
5
6
7
8
9

   page.on('dialog', async (dialog) => {
     if (dialog.type() === 'prompt') {
       console.log('Prompt message:', dialog.message());
       await dialog.accept('Response from Puppeteer'); // Provide a response and accept the prompt dialog
       // Or use dialog.dismiss() to dismiss the prompt dialog
     }
   });
   

When thedialog.type() returns'prompt', it means a prompt dialog has appeared. You can retrieve the message usingdialog.message(). In this example, the prompt message is logged to the console, and then theaccept() method is called to provide a response and accept the dialog. Alternatively, you can usedialog.dismiss() to dismiss the dialog. 4. Triggering JavaScript dialogs: To simulate the appearance of JavaScript dialogs for testing purposes, you can usepage.evaluate() to inject JavaScript code that triggers the dialogs:

1
2
3
4
5
6

   await page.evaluate(() => {
     window.confirm('Are you sure?');
     // Or use window.prompt('Please enter your name:', 'John Doe');
   });
   

Thepage.evaluate() method is used to execute the JavaScript code within the page context. In this example, it triggers a confirm dialog usingwindow.confirm(). Similarly, you can usewindow.prompt() to trigger a prompt dialog. By combining these steps, you can handle JavaScript dialogs (such as confirm and prompt dialogs) with Puppeteer. Whenever a dialog appears on the page, it will be intercepted and handled accordingly, allowing you to automate interactions with JavaScript dialogs.