Please refer the below set of code to understand how can we switch between different windows in Selenium.
Open a web page:
Switch between two tabs or windows:
(1)
If you want to switch to a specific window, see below:
Now if you want to switch to second windows use the below code:
(2)
Or, simply you can do as below to switch between two tabs or windows:
WebDriver driver = new FirefoxDriver(); driver.get("http://aksahu.blogspot.in/");Open a new window:
WebElement elemLink = driver.findElement(By.linkText("Web Driver")); Actions actions = new Actions(driver); actions.moveToElement(elemLink); actions.contextClick(elemLink).sendKeys(Keys.ARROW_DOWN) .sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build() .perform();For opening in a new tab/window see the post Open in new Tab or new Window in Selenium Webdriver
Switch between two tabs or windows:
(1)
If you want to switch to a specific window, see below:
String windowHandle = driver.getWindowHandle();
Now if you want to switch to second windows use the below code:
for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); }Switch to the parent window:
driver.switchTo().window(windowHandle);
(2)
Or, simply you can do as below to switch between two tabs or windows:
ArrayListtabs = new ArrayList (driver.getWindowHandles()); //Switch to new window driver.switchTo().window(tabs.get(1)); driver.close();//do some action in new window(2nd tab) //Switch to main/parent window driver.switchTo().window(tabs.get(0)); driver.getTitle();//do some action in main window(1st tab)