The Issue
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 Answer
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.
The Code
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# Example for driver.close() require 'selenium-webdriver' require 'rspec/expectations' include RSpec::Matchers Selenium::WebDriver::Chrome.driver_path="CHROME-DRIVER-PATH" @driver = Selenium::WebDriver.for :chrome # Opening 3Qi Labs website in one tab @driver.get 'https://3qilabs.com/' # Opening a new browser tab @driver.execute_script "window.open('');" # Switch to the new tab to perform some actions @driver.switch_to.window(@driver.window_handles[1]) # Opening Google home page @driver.get("https://www.google.com/") puts "Closing Google" # closing the active tab @driver.close() # Switching to the first tab @driver.switch_to.window(@driver.window_handles[0]) # Opening YouTube in the first tab @driver.get("https://www.youtube.com/") puts "Closing YouTube" # Close the only tab left, which will close the browser. @driver.close() |
1 2 3 4 |
#Result after executing the above code Closing Google Closing youtube |
The Result
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
The Takeaway
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.