Search code examples
rubyiframewatir

How can I change the focus from an iframe back to main page using watir?


I have a nested iframe that looks something like this

<iframe class="first">
   <button></button>
   <iframe class="second">
      <button></button>
   </iframe>
</iframe>

I switched into the second iframe to work with elements within that iframe, and now I want to go back and work with elements in the first iframe. But I can't get out of the iframe using watir for some reason...

I've tried using $b.frame(index: 0).locate - I get an "unable to locate frame" error

I've also tried doing $b.iframe(class: "first").locate, but that didn't work either

Please help!


Solution

  • Watir handles browser context switching for you. You only need to include the full iframe path in the definition of the element.

    Watir lazy loads so this doesn't actually locate them, just stores their location information

    b1 = browser.iframe(class: 'first').button
    b2 = browser.iframe(class: 'first').iframe(class: 'second').button
    

    To click the second button, Watir will automatically switch into first frame context, then the second frame context, then click that button

    b2.click
    

    Watir will automatically switch between any browsing contexts without needing to be explicitly specified:

    b1.click
    b2.click
    b1.click
    

    You shouldn't need to explicitly change contexts, just interact with the next element you need to use, but either of these will get you back to the top level browsing context:

    browser.exist?
    browser.iframe.exist?