New Tab Window handling using Selenium WebDriver

Selenium : New Tab Window handling

Tab is same like window. There is no difference with respect to selenium. There is difference at code level, I mean HTML code level. But for selenium automation both are the same.So, automating the new tab content is same like window.
You have to use switchTo().window()
Run below 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
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 tab
*
*/

public class newTabHandling {

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 second product to open window: Bag
driver.findElement(By.xpath("//div[@class='product2View']/a")).click();

//Now here is the New Tab handling code

//Get All Tabs or Window 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

×