Introduction
Hello readers, today in this article we will learn about Handling a new browser window or tab in Watir. Watir stands for Web Application Testing in Ruby. Using the window
class, you can handle new browser tabs or windows that open during the test. The window class allows us to switch between different browser windows or tabs. Let’s see how you can handle new browser tabs in Watir Ruby.
Handling a new browser window in Ruby.
Handling a new browser window in Ruby is not so hard, During the test when you click a link or perform an action that opens a new browser tab or window, you have to switch to that new tab to interact with its elements or contents. For that first, you need to save the identifiers of new open windows and then switch to the new tab.
require 'watir'
# Initialize the browser
browser = Watir::Browser.new :chrome
# Open a webpage
browser.goto 'https://www.example.com'
# Click a link that opens a new tab/window
browser.link(id: 'link_element_id').click
# Store the handles of all open windows/tabs
original_window = browser.window
# Switch to the new tab/window
new_window = browser.window(title: 'New Tab web page title')
new_window.use
# Perform actions in the new tab/window
# ...
# Switch back to the original tab/window
original_window.use
# Close the browser
browser.close
Switching Between Tabs
To switch to the new browser tab or window you can use use
method
# Switch to a specific window/tab by its title
browser.window(title: 'New Tab web page title').use
# Switch back to the original window/tab
original_window.use
Handling Multiple Tabs
If you have multiple new tabs in your web browser and you want to switch between them based on their order, you can simply use windows
method.
# Get an array of all open windows/tabs
all_windows = browser.windows
# Switch to the first window
all_windows[0].use
# Switch to the second window
all_windows[1].use
Closing a Browser Tab
To close the browser tab/window you can use close
method.
# Close the current tab/window
browser.window.use.close
Remember that the above code snippets are only for example and might need to be adapted to your specific use case and website structure. Also, Watir provides different attributes to locate browser windows, for example, by title, URL, and index, so you can choose any of these based on your testing needs. If you are interested in exploring more on Browser Window in Ruby Watir, you can simply read the documentation provided by Watir.