Search code examples
watir

How do I close the child window and start operating on first window


When I write

b.windows.last.use do
  b.link.click
end

Once after the click, WATIR automatically switch back to first window, now I can start operating on first window, but I don't know how to close this child window and start operating on first window. I could do it in selenium but I don't know how to do it in WATIR.

What I have tried

require 'watir'
driver = Selenium::WebDriver.for :firefox
b = Watir::Browser.new driver
b.goto("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open")

b.iframe(id: 'iframeResult').element(xpath: "//button[contains(text(),'Try it')]").click
firstWindow=b.windows.first

b.windows.last.use do
  b.element(text: 'LEARN HTML').click
end #end of this block automatically switch back to first window.

b.windows.last.close #Closing the child window 

#b.iframe(id: 'iframeResult').element(xpath: "//button[contains(text(),'Try it')]").click 
#This above line is not working so made a switch in the following line

firstWindow.use do #but it's not working as expected too.
  b.iframe(id: 'iframeResult').element(xpath: "//button[contains(text(),'Try it')]").click
end

WATIR allows me to operate on the parent window through automatic switch but if I close the child window after this automatic switch, I don't have any way to connect back to the parent window even though automatic switch was done or connection to the parent window lost.


Solution

  • Ah, looks like a performance enhancement we made resulted in a bug collision with Firefox - https://github.com/mozilla/geckodriver/issues/610

    First, I personally avoid using blocks when working with windows, so my code would look like this:

    b.window(url: 'https://www.w3schools.com/').use
    # do things
    b.window.close
    b.original_window.use
    

    The problem is that because the element that opened the second window was inside an iframe, when Watir switches back to the first window, Firefox keeps the browsing context in the iframe instead of restoring it to the top level context. Watir used to always reset it with every element lookup, but those were extra wire calls, so we cached the context and now only make the call to switch to the top when necessary.

    The temporary workaround until Mozilla fixes that bug is to do:

    b.wd.switch_to.default_content