Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

package suite1;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.Set;
public class HandlingMultipleWindowsTestNG {
private WebDriver driver;
private String mainWindow;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium_Java\\chromedriver-win64\\
chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.amazon.in/s?k=mobiles&ref=nb_sb_noss_2");
mainWindow = driver.getWindowHandle();
System.out.println("Main window ID: " + mainWindow);
}
@Test
public void testMultipleWindows() {
WebElement ele = driver.findElement(By.xpath("//span[@class='a-size-medium a-color-base a-
text-normal']"));
ele.click();
WebElement ele2 = driver.findElement(By.xpath("(//span[@class='a-size-medium a-color-base a-
text-normal'])[2]"));
ele2.click();
Set<String> winIds = driver.getWindowHandles();
System.out.println("All window IDs: " + winIds);
String tabWindow = "";
String expTitle = "Apple iPhone";
String actual = "";
for (String winId : winIds) {
if (!winId.equals(mainWindow)) {
tabWindow = winId;
driver.switchTo().window(tabWindow);
actual = driver.getTitle();
System.out.println("Switched to window ID: " + tabWindow + " with title: " + actual);
if (actual.contains(expTitle)) {
break;
} else {
driver.close();
}
}
}
driver.findElement(By.id("buy-now-button")).click();
driver.switchTo().window(mainWindow);
}
@AfterTest
public void tearDown() {
driver.quit();
}
}

/*
* OUTPUT:
*
* [RemoteTestNG] detected TestNG version 7.4.0 Apr 10, 2024 10:25:03 AM
* Main window ID: E166278C90FC61B84A240B2DAB2EDC81 All window IDs:
* [E166278C90FC61B84A240B2DAB2EDC81, 3C0E755E3F3426CB296E5B6449A9DC46,
* 6FBDCF70A88F183817E7509EB1B46F8C] Switched to window ID:
* 3C0E755E3F3426CB296E5B6449A9DC46 with title: Switched to window ID:
* 6FBDCF70A88F183817E7509EB1B46F8C with title: Apple iPhone 13 (128GB) - Blue :
* Amazon.in: Electronics PASSED: testMultipleWindows
*
* =============================================== Default test Tests run: 1,
* Failures: 0, Skips: 0 ===============================================
*
*
* =============================================== Default suite Total tests
* run: 1, Passes: 1, Failures: 0, Skips: 0
* ===============================================
*
*/

You might also like