How to set WATIR focus on new window
Asked Answered
E

5

6

I'm new to WATIR testing (and do I love it!) and have run into a wall on how to refocus my WATIR script to a newly opened window.. Here's my (simplified) script....

#!/usr/bin/ruby
require 'rubygems'
require 'watir-webdriver'
browser=Watir::Browser.new
browser.goto("http://0:3050")

browser.text_field(:name,"userkey300203830").set("OKJHNB")
browser.button(:id, "interview48").click

puts "Expected Result:"
puts "A successful display of cars"

if browser.window(:title=>"300203830").exists?
   puts " Test passed. New window opened!"
else
   puts " Test Failed! No window found"
end

It all works right up to the end. After the key "interview48" is clicked, a new window is opened with the title "300203830". Looks like I find it but I just don't know how to now focus on that window.

Emptor answered 22/5, 2012 at 19:1 Comment(0)
I
7
browser.window(:title => "300203830").use do
  # do something
end

More information: http://watir.github.io/docs/browser-popups/

Invalidate answered 22/5, 2012 at 19:30 Comment(0)
K
7

Additionally for more than 2 windows you can use the following:

browser.windows[n].use  

#n is variable for which window. n will access them in order of opened or tabs from left to right

Kaylyn answered 20/7, 2012 at 15:31 Comment(0)
K
6
browser.windows.last.use 
browser.windows.first.use

You can use the above commands if you open a new window from first browser instance and would like to toggle between the two.

Kaylyn answered 18/6, 2012 at 21:47 Comment(1)
This one seemed to not fail when there is only one window present, as opposed to browser.windows[n].use. Just a tidbit of information for anyone who might be interested in that distinction.Garratt
T
1

There are 3 primary selectors for windows:

  • :title - typically the easiest

  • :url - often used with a Regexp value

  • :element - a unique element might be the least brittle (new as of Watir 6.18!)

    browser.window(title: 'new window') browser.window(url: /my_page.html/) browser.window(element: browser.div(id: 'my-element'))

Locating by index is no longer supported

More information: Watir Browser Windows

Titlark answered 25/3, 2021 at 13:25 Comment(0)
G
0

If there is only one other window you want to use, so as of Watir 6.18, the easiest way to work with that window is with Browser#switch_window. It can only be used if there are only 2 windows, and all it does is switch to the other one, no additional locating required.

browser.switch_window
Gehenna answered 13/11, 2022 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.