How to Handle Alerts and Frames in WebDriver

This is Part 5 of the Selenium WebDriver Tutorial Series. Check out Part 4 to learn about better Window Handling.

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.


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.

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.

Get Alert Text

We can get the text from the alert using getText() method

Accept or Dismiss the Alert

We can accept(OK) or dismiss(Cancel) the alert using accept() and dismiss() methods.

Type on Alert

If the alert has a textbox, we can type on it using sendKeys() method

Authenticate Using Alert

We can handle basic authentication (username and password alert) using authenticateUsing() method.

SEE ALSO:   3 Things to Avoid in Test Automation

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.

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

Hope this post was helpful to you. Subscribe to our newsletter to get updates on upcoming WebDriver tutorials.

Automation Testing Tutorials, Tips, Solutions & more once a week


Further Reading:

Next Post : Selenium WebDriver setup with Maven

You may also like...

2 Responses

  1. Vinay says:

    Didnt know about handling authentication alerts. Thanks for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *