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).

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.