What are JS Alerts ?
An alert box is often used if you want to make sure information comes through to the user.
JavaScript has three kind of popup boxes:
- Alert box,
- Confirm box, and
- Prompt box.
alert(), confirm(), prompt() dialogs
By default, dialogs are auto-dismissed by Playwright, so you don't have to handle them. However, you can register a dialog handler before the action that triggers the dialog to either Dialog.accept() or Dialog.dismiss() it.
page.onDialog(dialog -> System.out.println(dialog.message()));
Note :
If there is no listener for Page.onDialog(handler), all dialogs are automatically dismissed.
For Prompt alert we need handle explicitly write page listener onDialog methods
page.onDialog(dialog -> {
System.out.println(dialog.message());
//dialog.accept("Accepting with Entered data");
dialog.type();
dialog.dismiss();
//dialog.accept("Accepting with Entered data");
});
Example web sites :
https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo
https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo
Sample Program as below
package com.example;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
public class Alerts2Example {
public static void main(String[] args) {
Playwright playwright = Playwright.create() ;
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(false)
.setChannel("chrome"));
Page page = browser.newPage();
// page.navigate("https://web-scraping.dev/product/1?variant=orange-small");
// page.locator("//button[contains(@class,'btn btn-secondary')]").click();
// page.locator(".cart-icon").click();
// page.locator("//button[normalize-space(text())='Clear']").click();
page.navigate("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo");
// page.locator("(//button[contains(@class,'btn btn-dark')])[1]").click();
page.onDialog(dialog -> {
System.out.println(dialog.message());
//dialog.accept("Accepting with Entered data");
dialog.type();
dialog.dismiss();
//dialog.accept("Accepting with Entered data");
});
page.locator("(//button[contains(@class,'btn btn-dark')])[2]").click();
// page.locator("(//button[contains(@class,'btn btn-dark')])[3]").click();
}
}
Comments
Post a Comment