Automation scripts often quit the browser application once the tests are completed. This is not always ideal, as there might be scenarios where a user will need to continue running the script on a different browser tab, within the same window and browser session.
The solution to the above-mentioned problem of closing only a particular tab can be resolved by using the close() function which is provided by Selenium Webdriver. This is a specific targeted method to close browser tabs, instead of quitting the browser itself.
Let us see the implementation of the close() function. In this example, we will switch between browser tabs (a function explained in How To Switch Between Multiple Browser Windows Using Ruby & Selenium WebDriver).
# Example for driver.close()
@driver = Selenium::WebDriver.for :chrome
# Opening 3Qi Labs website in one tab
# Opening a new browser tab
# Switch to the new tab to perform some actions
# Opening Google home page
puts "Closing Google"
# closing the active tab
# Switching to the first tab
# Opening YouTube in the first tab
puts "Closing YouTube"
# Close the only tab left, which will close the browser.
#Result after executing the above code
The above code illustrates the following
- Opens a new browser
- Navigates to “3Qi Labs website” in the first tab
- Opens a new tab and switches to this new tab
- Navigates to “Google Home Page”
- Closes the “Google Home Page” tab
- Switches to the “3Qi Labs website” tab
- Navigates to the “YouTube Home Page” in the same tab
- Closes the current tab and window
It is important to understand the concept of close(), which can help the user close unnecessary tabs, and still keep the other tabs open to continue with the rest of the automation.