sashoalm
sashoalm

Reputation: 79467

Switch to top-level frame with Selenium

What is the best way to switch to the top-level frame in Selenium if I'm unsure of the nesting level?

I tried using this code, but ParentFrame() doesn't throw an exception if you are already at top-level so it doesn't work.

while (true)
{
    try { driver.SwitchTo().ParentFrame(); } catch { break; }
}

Upvotes: 1

Views: 1067

Answers (2)

Bhuvanesh Mani
Bhuvanesh Mani

Reputation: 1464

I got here when I faced similar problem and thought of sharing what I learnt.

driver.switchTo().defaultContent(); // this command takes driver to the top level of DOM irrespective of nested level

__________________________ top of DOM
|
|_________________________ iframe-1
|   |
|   |_____________________ iframe-1.1
|   |  |
|   |  |__________________ iframe-1.1.1 (driver.switchTo().parentFrame() takes driver to iframe-1.1)
|   |  |
|   |  |__________________ iframe-1.1.2
|   |
|   |_____________________ iframe-1.2 (driver.switchTo().parentFrame() takes driver to iframe-1)
|   |
|   |_____________________ iframe-1.3
|
|_________________________ iframe-2
|
|

Upvotes: 1

Norayr Sargsyan
Norayr Sargsyan

Reputation: 1868

If you want to return to the main content from Iframe use this

driver.switchTo().defaultContent();

Upvotes: 2

Related Questions