Selenium – Switching Windows

Posted on Posted in Selenium Java

Why Learn Switching Windows using Selenium?

You may come across certain automation scenarios that involve any of the following

  1.  An action on website causes a new browser tab to be launched.
  2.  Website shows some popups which may require some action.
  3.  An action on website causes new browser window to be launched.

And sometimes we ourselves might be interested in testing an application by using it from multiple tabs (e.g. GMail when multiple-tabs are opened, they all connect to same user account with which we are logged in).

Switching Windows in selenium is about learning how to write tests that can work with multiple browser windows or tabs in the same test.

Getting Ready

WebDriver  interface provides us three new functions using which we can code tests that involve dealing with multiple browser windows or tabs.  We just need to understand that each browser window or tab in selenium is identified by a unique string (which is automatically assigned)  this unique string is called Window Handle.  If there are two browser tabs opened and tab 1 is active, driver.findElement command will work for HTML code in Tab1 only.  If we want to click any button in page of Tab2, we first need to ask driver object to switch its context to tab 2 by giving Handle of tab 2.

Methods in WebDriver Interface for Switching Windows

Key methods that we would require to perform four common operations on any given alert are:

Exercise – 1

  1. Launch Browser
  2. Open Popup Test Website.
  3. Click MultiPopup Test link on the homepage of site (this will launch few popups).
  4. Print count of total new popups opened by the browser.
  5. Switch to each popup one by one and do the following
    1. Print the URL
    2. Print Page Title
  6. Close each pop-up one by one (don’t close the main website page)
  7. Quit the browser.

Exercise – 2

  1. Using Selenium Launch Browser
  2. Open Selenium New Tab Page
  3. Click Terms and Conditions link on the page.
  4. Verify that a new browser window or tab is launched.
  5. Switch to newly opened window.
  6. Print the Current URL and Title after switching.
  7. Click Agree button.
  8. Switch back to main window.
  9. Print Current URL and Title.
  10. Quit browser.