In website, you may have seen Java script alert which pops up for some cases. For example, While submitting invalid card details, you may get Java script alert explaining about the incorrect entered values.
Selenium WebDriver has the capabilities to handle these alerts via simple commands.
Selenium Provides Alert API to handle Java script alert.
accept() – Accept the alert
dismiss() – Reject the alert
getText() – Read the text displayed on alert
sendKeys() – To write text into InputBox displayed on alert
Command to switch the control to Java script alert :
You have to import a following package in your script for Alert API – import org.openqa.selenium.Alert
Alert alert = driver.switchTo().alert();
Sample code to accept the alert
Alert alert = driver.switchTo().alert(); alert.accept();
Sample code to reject the alert
Alert alert = driver.switchTo().alert(); alert.dismiss();
Sample code to write the text on alert
Alert alert = driver.switchTo().alert(); alert.sendKeys("Testing alert"); alert.accept();
Sample code to read the text displayed on alert
Alert alert = driver.switchTo().alert(); String text = alert.getText(); alert.accept();
If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.