HomeSelenium

Selenium Interview Question – How to switch to another window in Selenium?

Selenium Interview Question – How to switch to another window in Selenium?

Hi all,

The following is the Selenium Interview question along with its answer. If you are interested in finding out our complete list of Selenium Interview questions, you can refer to http://www.qafox.com/selenium-interview-questions/


Question: How to Switch to another window in Selenium?


Answer:  The following is the answer for this question:

The following predefined methods of Selenium can be used for handling the multiple windows in an application:

  • getWindowHandle() – for retrieving the window id of the currently focused window.
  •  getWindowHandles() – for retrieving the window ids of multiple opened windows
  • switchTo() – helps us in switching
  •  window() – used along with switchTo() and intakes window id as input

Example program:  The following program will capture all the opened windows, switch to child window and close it and later switch to the main window and then close it.

//Store all the currently opened windows in a Set Collection

Set<String> set = driver.getWindowHandles();

Iterator<String> itr = set.iterator();

//Store the window ID of the main window

String mainWindow = itr.next();

//Store the window ID of the child window

String childWindow = itr.next();

//Switch to child window

driver.switchTo().window(childWindow);

//Close the child window

driver.close();

//Switch to main window

driver.switchTo().window(mainWindow)

//Close the main window

driver.close();


If you are interested in finding out our complete list of Selenium Interview questions, you can refer to http://www.qafox.com/selenium-interview-questions/


Please leave your questions/comments/feedback below.

Happy Learning ?

Naveen Repala (www.QAFox.com)

Comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *

For FREE Testing Tutorials & Videos

X
Open chat
Contact Us on Whatsapp