Alerts Handling using Selenium WebDriver

Alerts Handling using Selenium WebDriver

For handling alerts on web page, Selenium provides four methods:

  • 1. accept() To accept the alert on web page
  • 2. dismiss() To dismiss the alert on web page
  • 3. getText() To get the text of the alert on web page
  • 4. sendKeys() To send some text to the alert on web page

Find below image and selenium code for the same

selenium webdriver window handling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package scripts;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class alertHandling {

public static void main(String[] args) throws InterruptedException {

//set Chromedriver path for Chrome browser
System.setProperty("webdriver.chrome.driver", "C:\\harshal personal\\selenium\\chromedriver.exe");

//create WebDriver object for Chrome
WebDriver driver = new ChromeDriver();

//open URL
driver.get("https://www.seleniumpoint.com/testwebsite.php");

//maximize the window
driver.manage().window().maximize();

//login to test web site
driver.findElement(By.id("remail")).sendKeys("test@seleniumpoint.com ");
driver.findElement(By.id("rpassword")).sendKeys("test@123");
driver.findElement(By.id("rsubmit")).click();

Thread.sleep(3000);

//click on View link of third product to open window: Car Seat
driver.findElement(By.xpath("//div[@class='product4View']/a")).click();

Thread.sleep(3000);

//get alert text
String alertText = driver.switchTo().alert().getText();
System.out.println("Alert Text is :" + alertText);

//Send value to alert
driver.switchTo().alert().sendKeys("01harshal.shewale@gmail.com");

//accept alert
driver.switchTo().alert().accept();

//dismiss alert
//driver.switchTo().alert().dismiss();


}

}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×