How to validate a text inside nested frames

Posted on

A frame is a separate HTML document embedded within another HTML document. When a web page contains frames, each frame is treated by the browser as a separate window. To interact with elements within a frame, we must switch WebDriver's focus to that frame.
To switch to a frame in Selenium, we can use the switchTo().frame() method. This method accepts the frame element, frame ID, frame name or the index as arguments.

After we are done with the actions in the frame, we switch back to the default content using the switchTo().defaultContent() method.
You can access the Example 1 from this link which contains nested frame with some text and we have to validate these texts.
In this example, you have three iframes in in the page. The first iframe contains another frame inside. First we have to switch to the first iframe. Hence we need to create a webElement object for first iframe. As there are no unique identifier available for first frame, we have to use the xpath. The xpath will be as follows:-

//div[@class='contentTextHeader' and contains(text(),'Example 1')]/following-sibling::iframe
We will be able to switch to the first frame using the above xpath. Then we can validate the text "Frame1 Div 1".

Now lets put everything together in Java Code:-
Java
Copy
WebDriver driver = new ChromeDriver();
driver.get("https://www.testautomationstudio.com/studio/frame/");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
// Find the frame element
WebElement frameElement = driver.findElement(By.xpath("//div[@class='contentTextHeader' and contains(text(),'Example 1')]/following-sibling::iframe"));
// Switch to the frame
driver.switchTo().frame(frameElement);
// Check if Frame1 Div 1 is displayed inside the frame
Assert.assertEquals(driver.findElement(By.id("frame1div1")).getText(), "Frame1 Div 1");
// Switch back to the default content
// Find the inner frame element
WebElement innerFrameElement = driver.findElement(By.xpath("//div[@id='frame1div1' and contains(text(),'Frame1 Div 1')]/following-sibling::iframe"));
// Switch to the frame
driver.switchTo().frame(innerFrameElement);
// Check if Frame1A Div 1 is displayed inside the frame
Assert.assertEquals(driver.findElement(By.id("frame1Adiv1")).getText(), "Frame1A Div 1");
driver.switchTo().defaultContent();
driver.quit();