Switching Between Browser Windows

When running Watir-Webdriver, your commands will affect the browser window that you have opened. If you open more than one browser window, your actions will still continue interacting with the parent window. If you wish to properly interact with the child browser windows, you will need to be able to switch the window you are running commands on.

https://awetest.zendesk.com/hc/en-us/article_attachments/200735227/WatirWindowSwitch1.png
 
 
With your browser windows open, you can switch between browsers using the command:


browser.driver.switch_to.window(browser.driver.window_handles[0])
browser.driver.switch_to.window(browser.driver.window_handles[1])

 
In this case, the [0] at the end signifies the parent window, which will be the first browser window you opened. By switching the [0] to [1], the child window will be selected, allowing you to execute commands in it. This can continue with 2,3,4,etc., increasing the index by 1 for each additional browser window. The image below demonstrates the script in action:
 
https://awetest.zendesk.com/hc/en-us/article_attachments/200735237/WatirWindowSwitch2.png
 
Here is the example debugging script for reference:
 
 
[1] pry(main)> browser.driver.switch_to.window(browser.driver.window_handles[0])
=> "4ffee036-8e48-5a47-984c-68f0e49180a5"
[2] pry(main)> browser.driver.switch_to.window(browser.driver.window_handles[1])
[2] pry(main)> browser.driver.switch_to.window(browser.driver.window_handles[1])
=> "4ffee036-8e48-5a47-984c-68f0e49180a5"
[3] pry(main)> browser.link(:text,/Visit Campus/).exists?
=> true
[4] pry(main)> browser.link(:text,/Visit Campus/).click
=> []

 
 
 
 
 
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.
Powered by Zendesk