Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer confirm

I am trying to learn puppeteer. I have successfully scripted a login to a page and some navigation. Then I have it click on a button. The page throws up a window.confirm and I want my script to accept this to continue to the next step but I can’t figure out how.

Can anyone point me in the right direction?

like image 887
Michael Bierman Avatar asked Apr 09 '18 08:04

Michael Bierman


2 Answers

Just done a simple test here, when a dialog box comes up on confirm. Simply pressing enter will close the dialog.

So what we can do in puppeteer, is do exactly that. I knocked up a quick webpage that had a confirm box,..

eg.

<div>Before confirm</div>
<script>
  window.confirm("confirm");
  document.write("<div>After Confirm</div>");
</script>

Now our puppeteer script.

await delay(1000);
await page.keyboard.press(String.fromCharCode(13));  
await page.screenshot({path: 'screenshot.png'});
await browser.close();

Doing the above my screenshot is

Before confirm
After Confirm

Exactly what we expect if pressing the confirm dialog,.. ps. delay is just a simple promises based setTimeout to wait, so we have chance for the confirm dialog to appear.

If you currently don't have a promise delay function, here is one for you to use.

const delay = (ms) =>
  new Promise((resolve) => setTimeout(resolve, ms));

UPDATE: Unfortunately dialogs don't respond the keypress reliably. But puppeter does have a dialog event we can attach too.

page.on("dialog", (dialog) => {
  console.log("dialog");
  dialog.accept();
});

You can even dismiss, and read what message etc was sent. more info here-> https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-dialog

like image 172
Keith Avatar answered Oct 04 '22 19:10

Keith


The confirmation prompt is triggered by the global function confirm(<string>) which is at window.confirm. That function freezes the execution of the script until a response is given, then returns it to the caller. If the user accepts the prompt the returned value will be true.

Since we're working on a custom browser session in a webpage you can overwrite globals with anything you want.

So before running the action that triggers the confirmation window run

await page.evaluate(`window.confirm = () => true`)

Then when the page code calls confirm() it will get a true response immediately without showing any prompt.

like image 24
fiatjaf Avatar answered Oct 04 '22 19:10

fiatjaf