How To Handle IFrames Using Selenium WebDriver

Posted By : Neha Dahiya | 25-May-2018

What is iFrame?

 

iFrame is nothing but an HTML document which is embedded in another HTML document. In HTML, it is defined as <iframe></iframe> tag. Firstly, we have to switch to the frame and then we can click using XPath. It is impossible to directly locate an iFrame on a webpage through XPath as it an iFrame so it is very important to understand to use iframes we have to switch between different iFrames present on a page. To switch between different iFrames “switchTo.frame” command is used to switch between differnet iFrames. “switchTo.frame” can be used in a number of ways:

 

1. Switch to the frame by Name:

Id and name are attributes used to switch between the frames.

Have a look at the iFrame HTML code which has the name attribute value “iframe1”. You can switch to the iFrame using command driver.switchTo().frame(“iframe1”). You can use the below code to switch iFrame by Name :

 

 

2. Switch to the frame by ID:

There is also an ID attribute similar to the name one. You can switch to the iFrame using command driver.SwitchTo().frame(“IF1”). Use the following code to switch iFrame by ID :

 

 

3. Switch to the frame by WebElement:

We can also switch through iFrame by passing iFrame WebElement to the driver.switchTo().frame() command. You will have to find the element which can be done using any locatorand then passing it to command. Below code can be used to switch iFrame by WebElement :

 

 

Switching back to Main page from Frame:

 

To perform any other operation outside the iFrame, it is very important to go back to the main page. A Main page is basically the page in which iFrames are embedded. switchTo().defaultContent(); command can be used to switch back to the main page. Use the following code:

 

 

 

 

Thanks!

Related Tags

About Author

Author Image
Neha Dahiya

Neha is a bright QA Engineer with skills in manual testing . Apart from finding bugs in application, she loves sketching and painting.

Request for Proposal

Name is required

Comment is required

Sending message..