How to handle iframe in Selenium WebDriver using java How to handle iframe in Selenium WebDriver using java selenium selenium

How to handle iframe in Selenium WebDriver using java


In Webdriver, you should use driver.switchTo().defaultContent(); to get out of a frame.You need to get out of all the frames first, then switch into outer frame again.

// between step 4 and step 5// remove selenium.selectFrame("relative=up");driver.switchTo().defaultContent(); // you are now outside both framesdriver.switchTo().frame("cq-cf-frame");// now continue step 6driver.findElement(By.xpath("//button[text()='OK']")).click(); 


You have to get back out of the Iframe with the following code:

driver.switchTo().frame(driver.findElement(By.id("frameId")));//do your stuffdriver.switchTo().defaultContent();


You need to first find iframe. You can do so using following statement.

WebElement iFrame= driver.findElement(By.tagName("iframe"));

Then, you can swith to it using switchTo method on you WebDriver object.

driver.switchTo().frame(iFrame);

And to move back to the parent frame, you can either use switchTo().parentFrame() or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();.

driver.switchTo().parentFrame();    // to move back to parent framedriver.switchTo().defaultContent(); // to move back to most parent or main frame

Hope it helps.