Playwright Java handle single alerts and Multple alerts using onceDialog() and onDialog() respectively.

Sameera De Silva
3 min readOct 14, 2024

--

The diffeence

The difference

The code is as per below

package com.sam.scripts;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.RecordVideoSize;
import com.microsoft.playwright.options.WaitForSelectorState;
import org.testng.annotations.Test;

import java.nio.file.Paths;
import java.util.Arrays;

/*
Caution
Don't use page.onDialog() when there are multiple different alerts
,always use page.onceDialog() why is that ?

Using page.onceDialog() is preferred because it sets up a one-time event listener for dialog events.
This means it will only handle the next dialog that appears and then automatically remove itself.
This is particularly useful in scenarios where multiple dialogs can be triggered, like in your case with different alerts.


page.onDialog()
is used when you want to handle the same alert or dialog multiple times during the execution of your script.

page.onDialog(alert -> {
// Get the alert text
String firstAlertText = alert.message();
// Accept the alert (click OK) do cancel use alert.dismiss()
alert.accept();
});
*/

public class AlertJavaScriptHandleMultple {

@Test(description = "Handle Java Script Alerts")
public void javaScriptAlerts() throws InterruptedException {
Playwright playwright = Playwright.create();

// Launch the browser with the argument to start maximized
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setArgs(Arrays.asList("--start-maximized"))
.setHeadless(false)); // Set headless to false

// Create a new browser context with video recording options
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setViewportSize(null) // Keep it null for maximization
.setRecordVideoDir(Paths.get("videos/")) // Set the video directory
.setRecordVideoSize(new RecordVideoSize(1280, 720)) // Set the video size
);

Page page = context.newPage();
// Set default timeout to 30 seconds (30000 milliseconds)
page.setDefaultTimeout(30000);

// Navigate to the URL and wait for the navigation to complete
page.navigate("https://the-internet.herokuapp.com/javascript_alerts");

// 01 - Alert with OK button---------------------------
// Locate the button using XPath and its text
Locator firstJsAlertButton = page.locator("//button[text()='Click for JS Alert']");
// Wait for the button to be visible and clickable
firstJsAlertButton.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE).setTimeout(60000) // Optional: Set a timeout for waiting
);

// Set up an event listener for the first dialog (alert)
page.onceDialog(alert -> {
// Get the alert text
String firstAlertText = alert.message();
System.out.println("Actual alert Text (Alert)=" + firstAlertText);

// Assert the alert text here
assert firstAlertText.equals("I am a JS Alert") : "Alert text does not match the expected value.";
// Accept the alert (click OK)
alert.accept();
});

// Trigger the first alert by clicking the button which opens the Alert
firstJsAlertButton.click();
System.out.println("01 Alert handled");

// After handling, there is a text as You successfully clicked an alert
Locator resultText = page.locator("//p[text()='You successfully clicked an alert']");
System.out.println("Result text after clicking the alert =" + resultText.textContent());

Thread.sleep(6000); // Wait for alert handling

// 02 - Alert with OK and Cancel button
// Locate the confirm button using XPath and its text
Locator confirmButtonOpenSecondAlert = page.locator("//button[text()='Click for JS Confirm']");
confirmButtonOpenSecondAlert.waitFor(new Locator.WaitForOptions()
.setState(WaitForSelectorState.VISIBLE)
.setTimeout(60000)); // Wait for the confirm button to be visible


page.onceDialog(alert -> { // This event listener is specifically for the confirm dialog
// Get the alert text
String secondAlertText = alert.message();
System.out.println("Actual alert Text (Confirm)=" + secondAlertText);
// Assert the alert text
assert secondAlertText.equals("I am a JS Confirm") : "Second Alert text does not match the expected value.";
// Click Cancel on the confirm dialog
alert.dismiss(); // This simulates clicking the Cancel button
});

// Trigger the confirm dialog by clicking the button for second alert
confirmButtonOpenSecondAlert.click();
Thread.sleep(4000); // Wait for a moment to allow the dialog to process

// After handling, there is a text as You clicked: Cancel
Locator resultTextCancel = page.locator("//p[text()='You clicked: Cancel']");
System.out.println("Result text after clicking the confirm alert =" + resultTextCancel.textContent());


// 03 Third alert
// Locate the button using XPath and its text
Locator thirdJsAlertButton = page.locator("//button[text()='Click for JS Prompt']");
// Wait for the button to be visible and clickable
thirdJsAlertButton.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE).setTimeout(60000) // Optional: Set a timeout for waiting
);

// Use onceDialog for the prompt
page.onceDialog(dialog -> {
// Get the prompt text message in the alert
String promptText = dialog.message();
System.out.println("Actual prompt Text (Prompt)=" + promptText);

// Assert the prompt text
assert promptText.equals("I am a JS prompt") : "Prompt text does not match the expected value.";

// Enter text into the alert's text field and click OK button.
dialog.accept("HELLO");

});
// click the button that opens the third alert so above onceDialog will be used.
thirdJsAlertButton.click();

// After typing, there is a text as You entered: HELLO
Locator resultTextEnteredValue = page.locator("//p[text()='You entered: HELLO']");
System.out.println("Entered value is =" + resultTextEnteredValue.textContent());
Thread.sleep(12500);

// Close the context and browser after completion
context.close();
browser.close();
playwright.close();

}
}

--

--

No responses yet