Handle Alert in Playwright Java

Profile picture for user arilio666

Dialog boxes on a web page can be used to raise an alert, to get confirmation on any input, or to have a kind of input from the users. 

 

Using playwright java, we can easily handle dialog alerts.

  • We will be using the autopract site for working around various dialogs.

 

Demo Link: http://autopract.com/selenium/alert5/

 

1.) Alert Dialog

 

Let us first click on the trigger alert button.

 

 

This shows us how we can handle it in playwright java.

 

Playwright playwright = Playwright.create();

Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

BrowserContext newContext = browser.newContext(

new Browser.NewContextOptions().setRecordVideoDir(Paths.get("Videos/")).setRecordVideoSize(1280, 720));

Page page = newContext.newPage();



page.navigate("http://autopract.com/selenium/alert5/");



page.onDialog(dialog -> {



dialog.accept();



});



page.locator("#alert-button").click();



newContext.close();

playwright.close();

 

Here we have used the onDialog to say the page when the alert pops up within the callback. We are accepting the alert using accept().

 

Now let us click on "Trigger a Confirmation."

The following alert pops up using the same java code. With the help of dismiss() method, we can ignore this alert.

 

Playwright playwright = Playwright.create();

Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

BrowserContext newContext = browser.newContext(

new Browser.NewContextOptions().setRecordVideoDir(Paths.get("Videos/")).setRecordVideoSize(1280, 720));

Page page = newContext.newPage();



page.navigate("http://autopract.com/selenium/alert5/");



page.onDialog(dialog -> {



dialog.dismiss();



});



page.locator("#confirm-button").click();



newContext.close();

playwright.close();

 

2.) Prompt Alert

 

Let us click on "Trigger A Prompt."

 

 

  • Here 10 is the default value. If you click on the OK button after any value in input, say 15, you will see the message You have entered number: 15 just above Trigger an Alert button, and if you click on the Cancel button, you will see  You have entered number: null message.

 

Playwright playwright = Playwright.create();

Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

BrowserContext newContext = browser.newContext(

new Browser.NewContextOptions().setRecordVideoDir(Paths.get("Videos/")).setRecordVideoSize(1280, 720));

Page page = newContext.newPage();



page.navigate("http://autopract.com/selenium/alert5/");



page.onDialog(dialog -> {



dialog.accept("20");



});



page.locator("#prompt-button").click();



newContext.close();

playwright.close();

 

  • Using the accept() method, we can pass in the prompt message within it.