Window handling using Selenium WebDriver

Selenium : Window handling

Many times on web application we see contents opens in window. So, for automating the newly opened window using selenium, we must have to switch to that window.
Here is a code for the same. You can try this code by yourself. Just copy the code below and run locally using eclipse.

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
55
56
57
58
package scripts;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

/*
* Purpose of script is click on AddToCart button in new Window
*
*/

public class windowHandling {

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(4000);

//First Get parent window,means current window handle
String parentWindow = driver.getWindowHandle();
System.out.println("Parent Window Title " + driver.getTitle());

//click on View link of first product to open window: Nikon D50
driver.findElement(By.xpath("//div[@class='product1View']/a")).click();

//Now here is the Window handling code

//Get All windows handles and iterate using for each loop
for (String handle: driver.getWindowHandles()) {
System.out.println(handle);
driver.switchTo().window(handle);

}

//Click on Cart Button
driver.findElement(By.xpath("//button")).click();

//Go back to Parent window
driver.switchTo().window(parentWindow);
}

}

Comments

Your browser is out-of-date!

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

×