Testing / Selenium Interview questions
How do you handle iframes in Selenium?
Elements inside an iframe are not part of the main document's accessible DOM from WebDriver's perspective, so you must explicitly switch context into the frame before locating anything inside it.
driver.switchTo().frame("payment-frame"); driver.findElement(By.id("card-number")).sendKeys("4242424242424242"); driver.switchTo().defaultContent();
switchTo().frame() accepts a frame's name/id, its index among frames on the page, or a WebElement reference to the iframe itself - the last option is the most reliable since names and indices can change. After finishing work inside the frame, switchTo().defaultContent() must be called to return focus to the main page before locating anything outside the iframe again; forgetting this step is a very common cause of a sudden NoSuchElementException on an element that clearly exists.
More Related questions...