代码之家  ›  专栏  ›  技术社区  ›  Rajagopalan

如何关闭子窗口并在第一个窗口上开始操作

  •  0
  • Rajagopalan  · 技术社区  · 6 年前

    当我写作的时候

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

    点击之后,WATIR会自动切换回第一个窗口,现在我可以开始操作第一个窗口,但我不知道如何关闭这个子窗口并开始操作第一个窗口。我可以用硒做,但我不知道怎么用水做。

    我试过的

    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允许我通过自动切换来操作父窗口,但是如果在自动切换之后关闭子窗口,即使自动切换完成或与父窗口的连接丢失,我也无法连接回父窗口。

    1 回复  |  直到 6 年前
        1
  •  0
  •   titusfortner    6 年前

    啊,看起来我们做的一个性能提升导致了与Firefox的bug冲突- https://github.com/mozilla/geckodriver/issues/610

    首先,我个人在使用windows时避免使用块,因此我的代码如下所示:

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

    问题是,因为打开第二个窗口的元素在iframe中,当Watir切换回第一个窗口时,Firefox将浏览上下文保存在iframe中,而不是将其还原到顶级上下文。Watir过去总是在每次元素查找时重置它,但那些都是额外的有线调用,所以我们缓存了上下文,现在只在需要时调用切换到顶部。

    在Mozilla修复该错误之前,临时解决方法是:

    b.wd.switch_to.default_content