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

Testing Types

         Installation testing Main article: Installation testing An installation test assures that the system is installed correctly and working at actual customer's hardware. Compatibility testing Main article: Compatibility testing A common cause of software failure (real or perceived) is a lack of its compatibility with other application software, operating systems (or operating system versions, old or new), or target environments that differ greatly from the original (such as a terminal or GUI application intended to be run on the desktop now being required to become a web application, which must render in a web browser). For example, in the case of a lack of backward compatibility, this can occur because the programmers develop and test software only on the latest version of the target environment, which not all users may be running. This results in the unintended cons...

Install Jenkins and configure it to Run Maven with TestNg Selenium

Steps to Install Jenkins and configure it to Run Maven with TestNg Selenium Installation Step 1)  Go to  http://jenkins-ci.org/ and download correct package for your OS. Install Jenkins. Step 2)  Unzip Jenkins to specified folder. Run exe file as shown in following screenshot: Step 3)  In  Jenkins 1.607 Setup  window click on  Next  button. Step 4)  Click on  Install  button in the end. Step 5)  Once installation is done, navigate to the Jenkins Dashboard (http://localhost:8080 by default) in the browser window. Step 6)  Click on the  New Item  link to create a CI job. Step 7)  Select the Maven project radio button as shown in the following screenshot: Using the Build a  Maven Project  option, Jenkins supports building and testing Maven projects. Step 6)  Click on OK button. A new job with name "WebdriverTest" is created in Jenkins Dashboard. Step 7) ...

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