QualityScape Forum

Testing Styles => Automated testing => Selenium => Topic started by: John Gimber on April 27, 2017, 05:29:30 PM

Title: iFrames and how to access their content - using "driver.switchTo()"
Post by: John Gimber on April 27, 2017, 05:29:30 PM
So, you have a web page.
This web page contains a second page, embedded in an iframe.
How do you use Selenium to access the content within the iframe?

(http://www.qualityscape.co.uk/f/index.php?action=dlattach;topic=18.0;attach=4;image)

Well, it can be done, but it's not immediately obvious.

The xpath matching technique will work with the content it has in the main container page - but it won't see the content in the iframe page.

For example, if there is a form in the iframe contents, and it has a field called "origin"... Selenium won't be able to see it.  It can see as far as the iframe, but that's it.

Code: [Select]
WebElement myFrame = driver.findElement(By.xpath("codepath to iframe"));
driver.switchTo().frame(myFrame);

Now Selenium can access the form!

Code: [Select]
WebElement myOriginField = driver.findElement(By.xpath("//input[@id='origin']"));
myOriginField.sendKeys("Glasgow");

And in order to return to the main container page again...
Code: [Select]
driver.switchTo().defaultContent();