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