Author Topic: iFrames and how to access their content - using "driver.switchTo()"  (Read 6022 times)

Offline John Gimber

  • QA Test Manager
  • Administrator
  • Newbie
  • *****
  • Posts: 14
  • Karma: +0/-0
  • QualityScape FTW!
    • View Profile
    • QualityScape
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?



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();
« Last Edit: April 27, 2017, 05:33:46 PM by John Gimber »
Most people just don't understand QA.  Spread the good word!
QualityScape - Forum
View John Gimber's profile on LinkedIn