'Selenium webdriver | driver().switchTo().defaultContent() method is not switching the control back to parent window from multiple child windows

Selenium webdriver | driver().switchTo().defaultContent() method is not switching the control back to parent window from multiple child windows.

I am facing problem with respect to no of windows and not frames. When I click a button on parent window say wp, a new web window say w1 is getting generated and eventually one more window gets generated say w2 , I want to switch to control to wp so I am using

driver.switchTo.defaultContent()

but its not switching control to parent window.



Solution 1:[1]

are you looking for switching to window tabs or iframe ?

for frames : we need to do,

driver.switchTo().defaultContent();
driver.switchTo.parentFrame();

for windows :

String parentwindow = driver.getWindowHandle();
List<String> allwindows = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(allwindows.get(1));
driver.switchTo().window(parentwindow);

Solution 2:[2]

There are two similar methods that can be used while switching to parent frames, but there is a slight difference between them.

driver.switchTo().defaultContent() driver.switchTo().parentFrame()

E.g.: You have three frames i1,i2,i3 and you are on frame i3, when you use driver.switchTo.defaultContent(), it will take you to i1, whereas with driver.switchTo.parentFrame() control will switch to i2 i.e. immediate parent frame (parent frame of the current frame).

Solution 3:[3]

If the process opens multiple browser tabs, we need to use switchTo().window(window reference); to switch focus between the tabs.

// Save the initial tab as parentwindow 
String parentwindow = driver.getWindowHandle();

// Collect the tabs opened in a list
List<String> windows = new ArrayList<>(driver.getWindowHandles());

// Switch to window other than parentwindow
driver.switchTo().window(windows.get(1));

// Switch back to parentwindow
driver.switchTo().window(parentwindow);

Solution 4:[4]

I was using RemoteWebDriver for my cloud session where VM were running tests. Locally, it worked for me using $ driver.switchTo().defaultContent() $, but all of a sudden, it did not work with RemoteWebDriver. I resolved my issue using:

driver.switchTo().parentFrame();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayanth Bala
Solution 2 ZygD
Solution 3 pmadhu
Solution 4 Funky Monkey