Skip to main content

How to Handle Alerts and Frames in WebDriver

We come across mainly two types of alerts in web applications : window based alerts and web based alerts. Window based alerts cannot be handled by webdriver and we have to take the help of external tools for handling them. Here we discuss on how to handle alerts(web based) and frames using Selenium WebDriver.

Summary

  • Handle Alerts
  • Wait For Alert
  • Get Alert Text
  • Accept or Dismiss Alert
  • Type on Alert
  • Authenticate using Alert
  • Handle Frames
  • Identifying Frames
  • Switch to Frame
  • Switch to Main Content

Handle Alerts

We use driver.switchTo().alert() method to handle alerts in webdriver. It returns an Alert object using which we can the alert can be processed.
1
Alert alert = driver.switchTo().alert();
Wait For Alert
Most often, we may have to wait for the alert to come up. Instead of using Thread.sleep(), we can use WebDriverWait as shown below.
1
2
3
4
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
Get Alert Text
We can get the text from the alert using getText() method
1
String text = alert.getText();
Accept or Dismiss the Alert
We can accept(OK) or dismiss(Cancel) the alert using accept() and dismiss() methods.
1
2
alert.accept();
alert.dimiss();
Type on Alert
If the alert has a textbox, we can type on it using sendKeys() method
1
alert.sendKeys("String to type");
Authenticate Using Alert
We can handle basic authentication (username and password alert) using authenticateUsing() method.
1
alert.authenticateUsing(new UserAndPassword("username", "password"));

Handle Frames

Frames are used to embed other documents within a web page. Using webdriver, we cannot directly access the elements in a frame unless we switch to that frame.
Identifying Frames
We can know if an element is within a frame or not by right clicking on the element and seeing any context menu item related to frames. For eg, in chrome, if you right click on a frame, you get the below entries. You can also analyze the HTML page source to see if the elements are within <iframe> tag or not.
Handle Frame
Switch To Frame
We can switch to a frame using driver.switchTo().frame() method. As the parameter, you can provide the frame index, frame name or id or the WebElement object related to the frame.
1
2
3
4
driver.switchTo().frame("NameOrID");
driver.switchTo().frame(0);  // using index (first frame here)
WebElement iframe_element = driver.findElement(By.xpath("//locator/to/frame/element"));
driver.switchTo().frame(iframe_element);
After switching to the frame, you can perform normal operations in its elements.
Switch to Main Content
After switching to a frame, you can only access the elements within the frame and cannot access the elements in the main content. For switching back to the main content, use defaultContent() method
1
driver.switchTo().defaultContent();
Hope this post was helpful to you. Subscribe to our newsletter to get updates on upcoming WebDriver tutorials.

----------------------------------------------------------------------------------------------------

Better Window Handling


Window handling is one of the most frustrating areas in webdriver if not handled properly. Automation tester often face the problem of their script not being on the correct window, not making the proper window switches, closing of windows etc.
We will try to get some core concepts clear here so that you can avoid these issues or same time in resolving them.

Summary

  • Target attribute of Link
  • Current Window Handling
  • Switching between Windows
  • Wait for new window
  • Switching back to parent window

Target attribute of Link

Hyperlinks with target=_blank values opens the link in a new window (or tab), So in case you have to find out whether a link opens in the same window or new window, checking the value for target attribute of the hyperlink will help.

Current Window Handling

We can use the getWindowHandle method to get the current window handle. It returns a string which uniquely identifies the current window.
String currentWindowHandle = driver.getWindowHandle();
We can use getWindowHandles to get all the currently opened windows as a set of strings. Please note that this will only return the windows that was opened by this webdriver instance. The windows opened manually or by another webdriver instance will not be returned. The second part is important because, it allows us to run multiple webdriver instances parallelly without interference.
Set<String> allWindows = driver.getWindowHandles();
We can loop through the list of all windows to get windows other than the current one.
1
2
3
4
5
6
7
8
9
10
String currentWindowHandle = driver.getWindowHandle()
<String> allWindows = driver.getWindowHandles();
// Loops through the windows list
for(String windowHandle : allWindows){
    if(windowHandle.equals(currentWindowHandle)){
       // current window
    } else {
       // other window
    }
}

Switching between windows

Switching between windows is done using the handle obtained by either getWindowHandle or getWindowHandles methods.
Normally, before we click on a link which opens a new window(target=_blank), we should get the current window handle using driver.getWindowHandle(). Then we get all the window handles and switch to the other window. Below code switches to the window other than the current window. Note that if more than 2 windows are present, it switches to the second window.
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Switches to the window other than the current window.
 * @param currentWindow the current window handle.
 */
private void switchToOtherWindow(String currentWindow){
  Set<String> allWindows = driver.getWindowHandles();
  for(String window : allWindows) {
    if(!window.equals(currentWindow)) {
      driver.switchTo().window(window); // switches to the other window
    }
  }
}
As you can see, for switching to a new window, we have to provide the handle or name of the window to switch to.
driver.switchTo().window("windowHandle");
If we know the name of the window, we can use it directly without having to take all the window handles. We can find the window name using the javascript statement
window.name
You can get the value in Chrome by bringing up the Developer window (Right click any where on the page and select Inspect) > Console Tab > Type “window.name”Window HandlingPlease note that not all windows have the name attribute; though popup windows usually tend of have the attribute. If during switching windows, the window handle is not provided properly, we get errors like NoSuchWindowException, InvalidSwitchToTargetException etc. Also if we switch to the wrong window and try to perform some actions on any element,  we get NoSuchElementException as the page may not have the required element.

Wait for new window

Use would sometimes need a method to wait till the new window is opened up. I have given below a method which waits till a new window is opened based on the number of windows. You can modify the method to wait till a window of particular name is opened etc.

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
/**
 * * Waits till new window is opened * * @param noOfWindows Expected number of windows * @param
 * timeOut timeout in milli second
 */
public void waitForWindowToOpen(int noOfWindows, int timeOut) {
  int initCount = driver.getWindowHandles().size();
  if (initCount == noOfWindows)
    return;
  else {
    boolean foundWindow = false;
    long duration = 0;
    long startTime = System.currentTimeMillis();
    duration = (System.currentTimeMillis() - startTime);
    while (timeOut > duration && !foundWindow) {
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
      }
      foundWindow = driver.getWindowHandles().size() >= noOfWindows;
      duration = (System.currentTimeMillis() - startTime);
    }
    if (timeOut <= duration && !foundWindow) { // Throw Error
    }
  }
}

Switching back to parent window

Once we have completed our activities on the child window, we may have to switch back to the parent window. We may either have to close the child window and switch to parent or just keep the window open.
If we have to close the child window, use driver.close() followed by driver.switchTo().window(“handleOfParentWindow”); 
If we don’t need to close the child window, just use driver.switchTo().window(“handleOfParentWindow”); But keep in mind that the window is still open. So if we open a new window, getWindowHandles() method will return the parent window, the first child window and the newly opened window. So be careful while using a loop to switch to other windows.

Comments

Post a Comment

Popular posts from this blog

API Testing With Selenium WebDriver

REST API Testing Framework We will be creating a simple Rest Testing Framework in Java and JUnit that could be used for any testing scenarios. Rest Testing Framework Overview The framework should be able to execute the basic REST operations (GET, POST, PUT, PATCH, DELETE) and perform the validations on the code, message, headers and body of the response. The completed code can be accessed from my  GitHub account   from where you can collect and make modifications based on your requirements. Design We will be having three classes for the framework (in package com.axatrikx.controller ) RestExecutor  : Performs the HTTP operations using Apache Http Client RestResponse  : A javabean class to hold our response values (code, message, headers, body) RestValidator  : Validates the response with the expected values The package  com.axatrikx.test  holds the test scripts. Note: I will be using ‘ json-server ‘ to fake the REST API. Its a real handy tool to r

ExtentReports in Selenium Webdriver

ExtentReports in Selenium Webdriver What is ExtentReport? ExtentReports  is a HTML reporting library for Selenium WebDriver for Java which is extremely easy to use and creates beautiful execution reports. It shows test and step summary, test steps and status in a toggle view for quick analysis Download Download the jar below: Download ExtentReports 1.4 (1623)    Snapshot of Extent report After Executing the Script   Program Steps:  We are going to write three different testcases. Pass Warning Fail TestCase with Pass Result Navigate to http://www.guvi.in Click on Sign-in Enter the credientials Check the URL is correct or not after login   TestCase with Warning Result Verify with the Wrong URL (static String Afterloginfail="http://www.guvi.in/ ")    TestCase with fail Result Click on Menu Select Tech Challenges Verify With wrong URL. Source Code: import  java.io.File; import  java.io.IOException; import   java.sql

How to Compare Two Images in Selenium

How to Compare Two Images in Selenium Some time in testing we have to do image comparision as verification point. So, in this blog I expalin how to compare two images in selenium. I have created one function for compare two images. you can use directly into your framework. first of all you have to import below packages into your code. import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; Now, you can use below function for comparison of two images. 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 public boolean mCompareImages ( BufferedImage img1 , BufferedImage img2 ) { boolean bCompareImage = true ; try { if ( img1 . getWidth () == img2 . getWidth () && img1 . getHeight () == img2 . getHeight ()) { for ( int i = 0 ; i < img1 . getWidth (); i ++) { for ( int j = 0 ; j < img1 . getHeight (); j ++) { if ( img1 . get