How to switch to the new browser window, which opens after click on the button? How to switch to the new browser window, which opens after click on the button? selenium selenium

How to switch to the new browser window, which opens after click on the button?


You can switch between windows as below:

// Store the current window handleString winHandleBefore = driver.getWindowHandle();// Perform the click operation that opens new window// Switch to new window openedfor(String winHandle : driver.getWindowHandles()){    driver.switchTo().window(winHandle);}// Perform the actions on new window// Close the new window, if that window no more requireddriver.close();// Switch back to original browser (first window)driver.switchTo().window(winHandleBefore);// Continue with original browser (first window)


Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();


This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window

String parentWindow = driver.getWindowHandle();Set<String> handles =  driver.getWindowHandles();   for(String windowHandle  : handles)       {       if(!windowHandle.equals(parentWindow))          {          driver.switchTo().window(windowHandle);         <!--Perform your operation here for new window-->         driver.close(); //closing child window         driver.switchTo().window(parentWindow); //cntrl to parent window          }       }