To interact with elements inside a shadow DOM using Playwright, follow these steps:
page.$
.shadowRoot()
method on the parent element to get a reference to the shadow root.querySelector
or querySelectorAll
on the shadow root to find and interact with elements inside it.Here's an example using TypeScript and @playwright/test:
import { test, expect } from '@playwright/test';
test('interact with shadow DOM elements', async ({ page }) => {
await page.goto('https://ray.run/');
// Find an element with a shadow root
const parentElement = await page.$('#my-element');
// Get a reference to the shadow root
const shadowRoot = await parentElement.shadowRoot();
// Find an element inside the shadow root
const childElement = await shadowRoot.$('#my-child-element');
// Interact with the child element
await childElement.click();
});
In this example, you first find the parent element with ID "my-element" using page.$
. Then, you call its shadowRoot()
method to get a reference to its associated Shadow Root object. Finally, you use $
again on the Shadow Root object to find an inner child element with ID "my-child-element" and click it.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].