How to Handle IFrames in Playwright

 

Handling iframe in Playwright with Java involves accessing the frame object using Playwright's Frame class. Since elements inside an iframe are isolated from the main document, you need to switch to the Frame context first before interacting with any elements within it.
















Steps to Handle iframe in Playwright (Java):

  • Launch browser and navigate to the page
  • Locate the iframe using a selector
  • Get the Frame object from the iframe element
  • Use frame.locator(...) to interact with elements inside the iframe

Example Use Case:

Let’s say there's an iframe with a form input (example: on https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_text).


Java Code using Playwright:

import com.microsoft.playwright.*;

public class IFrameExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Navigate to a page containing an iframe
            page.navigate("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_text");

            // Wait for the iframe to load
            FrameLocator frameLocator = page.frameLocator("#iframeResult");

            // Locate input inside iframe and type text
            frameLocator.locator("input[type='text']").fill("Playwright Java");

            // Optional: Wait or assert
            page.waitForTimeout(3000);
        }
    }
}


Explanation:

  • page.frameLocator("#iframeResult") – Selects the iframe by its ID.

  • frameLocator.locator("input[type='text']") – Accesses the input element inside the iframe.

  • .fill("Playwright Java") – Fills text in the input box.

No comments:

Post a Comment