logo logo

Selenium Switch Methods (Chapter 5)

main post image

In this 5th and final Selenium article, we will dive into the Switch Methods. Switch Methods are designed for switching to frames, alerts, and windows. Our Test Script must switch before performing an action within the frame, alert, or window.  If we omit switching then the program returns an exception. Methods for switching are accessed through switchTo(). switchTo() returns a target locator and used for sending a future command. Here’s a list of methods via switchTo:

  • activeElement()
  • alert()
  • defaultContent()
  • frame
    • frame(int index)
    • frame(String nameOrId)
    • frame(WebElement frameElement)
  • parentFrame()
  • window(String nameOrHandle)

By the end of this article, you will read how to switch to a frame, alert, and window. Code will be located on GitHub https://github.com/RexJonesII/TestProject-TestNG.
Also, make sure to check out my latest article on all the latest updates to Selenium 4!

Tutorial Chapters

  1. Browser Methods (Chapter 1)
  2. WebElement Methods (Chapter 2)
  3. Navigation Methods (Chapter 3)
    • to
    • refresh
    • back
    • forward
  4. Wait Methods (Chapter 4)
    • pageLoadTimeOut
    • ImplicitWait
    • ExplicitWait
    • FluentWait
  5. You’re here → Switch Methods (Chapter 5)

Switch To Frame

There are 4 methods that allow us to select a frame and 1 method that changes focus to the parent context:

  1. frame(WebElement element) – selects a frame by WebElement.
  2. frame(String nameOrId) – selects a frame by its name or ID.
  3. frame(int index) – selects a frame by its (zero-based) index.
  4. defaultContent() – selects either the first frame or main document.
  5. parentFrame() – change focus to the parent context.

If an application has a frame, it will either be a frame or an iframe element. Although there’s a difference, we normally say “frame” for both elements. In spite of that, most applications contain an iframe which stands for inline frame. It’s designed for helping the application remain interactive.

We can tell the difference between frame and iframe by its window. A frame can be resized while an iframe cannot be resized within the application. Whether the application has a frame or iframe, we must always switch to the frame before performing an action. On TestProject’s Platform page, there’s an Intercom icon located within an iframe. Intercom allows us to start a conversation and ask TestProject anything.

TestProject Test Automation Platform

Notice, View frame source after right clicking the icon. View frame source informs us, the WebElement is located in a frame. We select Inspect and see an iframe tag.

iframe tag

Now, our automation Test Script begins with the following steps:

  1. Scroll to the bottom of TestProject’s Platform page.
  2. Wait using an Explicit Wait statement (covered in the previous article “Selenium Wait Methods”).
  3. Switch to the frame.
  4. Find the element.
  5. Click the element.
@Test
public void demoSwitchToFrame1 () {
  JavascriptExecutor js = (JavascriptExecutor) driver;
  js.executeScript("window.scrollBy(0,2000)");
  
  WebDriverWait wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("intercom-launcher-frame"));
  
  driver.findElement(By.className("e2ujk8f2")).click();
}
@Test
public void demoSwitchToFrame2 () {
  JavascriptExecutor js = (JavascriptExecutor) driver;
  js.executeScript("window.scrollBy(0,2000)");
  
  WebDriverWait wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.presenceOfElementLocated(By.name("intercom-launcher-frame")));
  
  driver.switchTo().frame("intercom-launcher-frame");
  driver.findElement(By.className("e2ujk8f2")).click();
}

Both Test Scripts work after switching to the iframe. The 1st Test Script switches to the frame within the wait statement “frameToBeAvailableAndSwitchToIt” then found and clicked the Intercom icon. This is the preferred way since 1 statement line waited for the frame and switched to the frame.

The 2nd Test Script shows how to switch to a frame without a wait statement: driver.switchTo().frame(“intercom-launcher-frame”). A NoSuchElementException would have shown up if there was not a switch statement. Here’s a screenshot after clicking the Intercom icon:

TestProject Support Chat

Switch To Alert

An alert is a pop-up box that provides information or expects an action from the user. There are 3 types of alerts and 4 actions to perform on an alert. The 3 types of alerts are:

  1. Information Alert – contains a message with 1 button.
  2. Confirmation Alert – contains a message with 2 buttons.
  3. Prompt Alert – contains a message with 2 buttons and a text entry field.

Actions to perform on the alert are:

  1. accept() – accepts the alert.
  2. dismiss() – cancels the alert.
  3. getText() – gets text from the alert.
  4. sendKeys() – types text into the alert.

Most of the time, an alert is shown with a gray disabled background. The web page is gray because an action cannot be carried out on the page. An action must be performed on the alert. On TestProject’s Blog page, a pop-up image resembling an alert provides information regarding a Complete E2E Automation Solution!

TestProject Blog

Hypothetically, if the pop-up image was an alert, the following Test Script switches to the alert then accepts the alert.

@Test
public void demoSwitchToAlert () {
  driver.get("https://blog.testproject.io/");
  driver.switchTo().alert().accept();
}

Switch To Window

Selenium assigns a unique alphanumeric id to all windows. The id is called a window handle and used to switch control between every window. There are 2 methods that get the window handle:

  1. getWindowHandle() – get the current window handle.
  2. getWindowHandles() – get a set of window handles.

We use the window handle for switchTo().window to switch focus between each window. A perfect example is TestProject’s Documentation page. The page loads in a new tab after clicking the Docs link via the Home page.

TestProject Home Page

TestProject Documentation

Let’s create a Test Script to perform the following steps:

  1. Get the Home Page window handle id.
  2. Click the Docs link.
  3. Get the Docs Page window handle id:
  4. Count the number of open windows.
  5. Print information for both open windows to show unique data:
    1. Window Handle
    2. URL
    3. Page Title
@Test
public void demoSwitchToWindow () 	{
  driver.get("https://testproject.io/");
  driver.findElement(By.id("menu-item-1727")).click();
  String mainHandle = driver.getWindowHandle();
  System.out.println("Home Page Window ID: " + mainHandle + "\n");
      
  Set <String> allHandles = driver.getWindowHandles();
  System.out.println("Windows Open After Clicking The Docs Link via Home Page: " + allHandles.size() + "\n");
  
  for (String windowHandle : allHandles) {
    if(mainHandle.equals(windowHandle)) {
      System.out.println("\t Window ID 1: \t" + windowHandle +
                      "\n \t URL: \t \t" + driver.getCurrentUrl() +						
                      "\n \t Title: \t \t" + driver.getTitle());				
    }	
    else	{
      driver.switchTo().window(windowHandle);
      
      System.out.println("\t Window ID 2: \t" + windowHandle +
          "\n \t URL: \t \t" + driver.getCurrentUrl() +						
          "\n \t Title: \t \t" + driver.getTitle());					
    }
  }
}

The following statement lines get the window handle and window handles:

  • String mainHandle = driver.getWindowHandle(): gets the Home Page window handle.
  • Set <String> allHandles = driver.getWindowHandles(): gets both window handles.

Here’s the results after getting the window handles and displaying information relevant to each page.

Selenium Switch Methods

  • Home Page Window ID and Window 1 have the same window handle “CDwindow-66A01C6DAF3805A30180709668B0A400” because they are the same window.
  • There are 2 open windows after clicking the Docs Link.
  • Window 1 displays a unique window handle with the correct URL and Page Title:
    • ID: CDwindow-66A01C6DAF3805A30180709668B0A400
    • URL: https://testproject.io/
    • Title: Free Test Automation For All – TestProject
  • Window 2 displays a unique window handle with the correct URL and Page Title:

That wraps all 5 Selenium Method Categories 🌟

  1. Browser Methods perform actions on a browser.
  2. WebElement Methods perform actions on WebElements.
  3. Navigation Methods loads a web page, refreshes a web page, or moves backward and forward in our browser’s history.
  4. Wait Methods pause between execution statements.
  5. Switch Methods switch to frames, alerts, and windows.

Happy Testing! 😎

Rex Jones II

About the author

Rex Jones II

Rex Jones II has a passion for sharing knowledge about testing software. His background is development but enjoys testing applications.

Rex is an author, trainer, consultant, and former Board of Director for User Group: Dallas / Fort Worth Mercury User Group (DFWMUG) and member of User Group: Dallas / Fort Worth Quality Assurance Association (DFWQAA). In addition, he is a Certified Software Tester Engineer (CSTE) and has a Test Management Approach (TMap) certification.

Recently, Rex created a social network that demonstrate automation videos. In addition to the social network, he has written 6 Programming / Automation books covering VBScript the programming language for QTP/UFT, Java, Selenium WebDriver, and TestNG.

Join TestProject Community

Get full access to the world's first cloud-based, open source friendly testing community. Enjoy TestProject's end-to-end test automation Platform, Forum, Blog and Docs - All for FREE.

Join Us Now  

Comments

6 1 comment

Leave a Reply

popup image

Selenium for Teams

Sharing and distributing Selenium tests has never been so easy! With TestProject's FREE Selenium based platform, you can finally create awesome tests with the freedom to collaborate with your team effortlessly.
Sign Up Now right arrow
FacebookLinkedInTwitterEmail