Handle ShadowDom in Playwright

  

What is Shadow DOM?

Shadow DOM is a web standard that enables encapsulation of HTML, CSS, and JavaScript in Web Components. It allows elements to have hidden DOM trees that are isolated from the main document DOM. This improves modularity and prevents style or script conflicts.



















Challenges with Shadow DOM in Automation

Because elements inside Shadow DOM are not part of the regular DOM, traditional selectors like page.locator("selector") won't work directly unless you pierce through the shadow boundary.


Handling Shadow DOM in Playwright Java

To handle Shadow DOM, you can use:

  • locator().evaluateHandle() to get the shadow root.
  • Then find the element inside that shadow root.

Sample Scenario

Let's say we want to automate a website that contains this structure:

<custom-element>
  #shadow-root
    <button id="myButton">Click Me</button>
</custom-element>




Java Code Example using Playwright


import com.microsoft.playwright.*;

public class ShadowDOMExample {
    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 sample page with Shadow DOM
            page.navigate("https://books-pwakit.appspot.com/");

            // Wait for the shadow host element
            Locator host = page.locator("book-app");
            // Access shadow root and query inside
            Locator searchInput = host.locator(">>> input#input");

            // Interact with the element inside shadow DOM
            searchInput.fill("Playwright");
        }
    }
}




Important Points:
  • ">>> input#input" is called deep selector in Playwright. It helps to pierce through shadow DOM boundaries.

  • Use locator(">>> selector") to access nested shadow DOM elements.

  • Works seamlessly in Playwright without needing custom JavaScript unless the DOM is deeply nested or dynamically built.

No comments:

Post a Comment