In this article, we will be discussing in detail how to handle shadow dom in Playwright. Let’s further deep dive and automate the below scenario:

1. Open https://books-pwakit.appspot.com/
2. Traverse through the shadow DOM and reach the input box
3. Write the keyword ‘Science’ and press the ‘Enter’ key to trigger a search
4. Validate that the book titled ‘What is Science?’ is visible on the search page

The best part of working with shadow dom’s in playwright is that you don’t have to write any extra code because playwright automatically traverses the shadow dom with CSS and text engines by default.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {test, expect} from '@playwright/test'

test.describe(
  'Example to demonstrate handling of Shadow DOM in Playwright',
  () => {
    test('Input a text in the input box and after search validate one of the book title', async ({
      page,
    }) => {
      await page.goto('https://books-pwakit.appspot.com/')
      await page.locator('#input').fill('Science')
      await page.keyboard.press('Enter')
      await expect(page.locator('text=What is Science?')).toBeVisible()
    })
  }
)

shadow dom test script in playwright

await page.goto(‘https://books-pwakit.appspot.com/’) – Opens the web page on a browser.

await page.locator(‘#input’).fill(‘Science’) – Traverses through the shadow dom to find the input box and enters the text ‘Science’ into it.

Let’s look into the DOM structure of our input box.

shadow dom structure

As you can see in the image our input (6) is behind multiple shadow roots, but since Playwright automatically traverses the Shadow DOM with CSS and text selectors, we are directly accessing our element using page.locator(‘#input’).

await page.keyboard.press(‘Enter’) – Presses the Enter key to trigger a search.

await expect(page.locator(‘text=What is Science?’)).toBeVisible() – In this case also our desired element is behind multiple shadow roots, so like above here also we are directly using a selector to access the element. Here instead of the CSS selector we are using a text selector and then we are asserting that the book titled ‘What is Science?’ is visible on the search page.

Upon execution, we should see that all tests are getting passed.

shadow dom playwright test execution summary

shadow dom playwright html report

Do check out 🙂

Github: https://github.com/alapanme/Playwright-Automation