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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With