Selenium Interview Question 9 – Difference Between getWindowhandle() and getWindowHandles()
As a part of Selenium Interview Questions series, in this post, we will learn differences between getWindowHandle() and getWindowHandles() in Selenium WebDriver.
A window handle is a unique identifier that is assigned to each window created. Selenium WebDriver provides you two methods getWindowHandle() and getWindowHandles() which are used to get window handle/s.
Differences between both are given below:-
- getWindowHandle() returns the window handle of currently focused window/tab. getWindowHandles() returns all windows/tabs handles launched/opened by same driver instance including all parent and child window.
- Return type of getWindowHandle() is String while return type of getWindowHandles() is Set. The return type is Set as window handle is always unique.
- In chrome and Firefox , Each tab in a window will have unique window handles. So getWindowHandles() will return handles for all tabs of a window. For example:- If there are four tabs in a window is opened, getWindowHandles() method will give “four” for chrome and firefox browsers. I am not sure about IE and EDGE. I will bring this in a new post.
- getWindowHandles() internally uses LinkedHashSet. So whatever Set it returns, it will give window handles in order it is opened.
Some important points where interviewer may confuse you:-
- As soon as you launch a browser window, it gets its window handle. It is not mandatory to load a URL in to it.
- If you close browser and then call getWidnowHandle() or getWindowHandles() on driver, you will get NoSuchSessionException stating “Session ID is null. Using WebDriver after calling quit()?“.
Example Program:-
package FeaturesExamples; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class WindowHandles { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); // I just launched browser. Did not load any URL System.out.println(driver.getWindowHandle()); // Quitting browser driver.quit(); // Calling get window handle method System.out.println(driver.getWindowHandles().size()); } }
If you have any doubt, feel free to comment below.If you like my posts, please like, comment, share and subscribe.#ThanksForReading
#HappyLearning