There are cases where we need to open new window and perform operations or there may be cases where after clicking on any button / link, it opens new window and need to perform operations on the new window.
Let us look into such example:
Test case: We need to open 'http://linkedin.com' and click on 'Help Center' link at the bottom which will open new window.
1. Verify the title of the new window
2. Verify text 'Welcome' on the page.
3. Search for a Question with text "Frequently Asked Questions" and verify the result.
package dayOne;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class NewWindow {
public static WebDriver driver;
@Test
public void verifySearchInNewWindow() throws InterruptedException {
driver = new FirefoxDriver();
driver.navigate().to("http://linkedin.com/");
driver.manage().window().maximize();
String mainHandle = driver.getWindowHandle();
//Wait for the element to be present
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".cust-svc-link")));
driver.findElement(By.linkText("Help Center")).click();
//Switch to new window and verify the title
waitForNewWindowAndSwitchToIt(driver);
String newTitle = getCurrentWindowTitle();
Assert.assertEquals(newTitle, "LinkedIn Help Center", "New window title is not matching");
//Verify the text present on the page
String textOnpage=driver.findElement(By.cssSelector(".welcome")).getText().trim();
Assert.assertEquals(textOnpage, "Welcome!");
//Verify search text on the page
String searchText="Frequently Asked Questions";
WebElement searchInputBox=driver.findElement(By.id("kw"));
searchInputBox.sendKeys(searchText);
WebElement searchButton = driver.findElement(By.cssSelector(".button.leftnoround.blue"));
searchButton.click();
WebElement resultedElement = driver.findElement(By.cssSelector(".rn_Element2"));
String resultedText = resultedElement.getText().trim();
System.out.println(resultedText);
Assert.assertTrue(resultedText.contains(searchText), "Search successfull");
closeAllOtherWindows(driver, mainHandle);
}
Remember : When ever we work on multiple windows, switching plays major role. We should switch to the desired window to perform operations and again switch back to default window to work on main window.