Home > Automation Testing > Code to Handle alert, window and iframe in Selenium

Code to Handle alert, window and iframe in Selenium

This post was most recently updated on June 14th, 2019

SwitchTo() Functions are used to handle alert, browser window and iframe.

driver.switchTo() functions are used to handle alert window, new tab or new window in browser and iframe within html document. 

Refer below table for switchTo functions and their uses:

switchTo functions  Uses
driver.switchTo().frame(index); Switch focus to iframe element using index of iframe in html document.
driver.switchTo().frame(“iframe_name”); Switch focus to iframe element using name of iframe
driver.switchTo().frame(webElement); Switch focus to iframe element using name of WebElement object.
driver.switchTo().parentFrame(); Switch focus to parent iframe element.
driver.switchTo().defaultContent(); Switch focus to main html document.
driver.switchTo().window(windowHandle); Switch focus to new window using window handle string
driver.switchTo().alert(); Switch focus to alert window or message box.
driver.switchTo().activeElement(); Switch to currently focused web element within html document

 

ActiveElement

Using this we can perform actions on currently focused element.

driver.switchTo().activeElement() → Used to find and perform action on current focused element.

Code:

 

Alert Window

driver.switchTo().alert() → Used to change focus from current active window to alert message box.

Code:

 

Browser window

driver.switchTo().window(windowHandle) → Used to change focus from current active window to new opened window.

Code:

 

IFrame within HTML Document

  1. driver.switchTo().frame(index) → Used to change focus to iframe within current web page content using no of iframe
    in page.
  2. driver.switchTo().frame(name) → Used to change focus to iframe within current web page content using iframe name attribute value.
  3. driver.switchTo().frame(webElementObject) → Used to change focus to iframe within current web page content using iframe webElement.
  4. driver.switchTo().parentFrame() → Used to change focus to parent iframe i.e. to outer iframe.
  5. driver.switchTo().defaultContent() → Used to change focus to normal web page.

 

Selenium Tutorial >>

This Article is TAGGED in , . BOOKMARK THE permalink.

Avatar photo
Neeraj Vishwakarma
Senior QA Engineer Skills: Automation Testing, Manual Testing, STLC, Java, Selenium Webdriver, Protractor, Database Testing.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">