Playwright Handle beforeunload Dialog

Profile picture for user arilio666

The beforeunload event is triggered when the user is about to leave the page, for example, by navigating to a different page or closing the browser tab. This event allows a website to display a dialog to the user, asking them to confirm that they want to leave the page. The beforeunload event is typically used to prevent the user from losing unsaved data.

We can register the dialogue handler when the page closes.

page.on('dialog', async dialog => {
 await dialog.dismiss();
});

or


     // Handle the beforeunload dialog
 page.on('dialog', async dialog => {
   // Get the message of the dialog
   console.log(dialog.message());
   // Accept the dialog
   await dialog.accept();
 });

We can either accept or dismiss the message.

  • Consider this scenario when we click this click beforeunload dialogue appears to redirect to the site.
const {test, expect} = require('@playwright/test');
test('DropDown', async ({page})=> 
{
     // Handle the beforeunload dialog
 page.on('dialog', async dialog => {
   // Get the message of the dialog
   console.log(dialog.message());
   // Accept the dialog
   await dialog.accept();
 });
await page.goto("file://D:/iVagus/Playwright/beforeUnload.html");
await page.locator("a[href='https://www.programsbuzz.com']").click();
});
  • We can see that the page has been redirected after handling the beforeUnload dialogue and when we dismiss it stays on that particular page.