The pierce selector in Puppeteer

The pierce selector in Puppeteer is an experimental feature that allows you to query shadow DOM elements more easily. Traditional CSS selectors don't pierce through shadow roots because they encapsulate their content to prevent styles and scripts from leaking in or out. The pierce selector solves this by bypassing the shadow DOM boundary and directly selecting elements within shadow trees.


How to Use the Pierce Selector in Puppeteer

Here’s an example of how to use it effectively:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  // Navigate to a page with shadow DOM
  await page.goto('https://example.com');

  // Select an element inside a shadow DOM using the pierce selector
  const element = await page.$('pierce:#shadow-element-id');

  if (element) {
    console.log('Shadow element found!');
    await element.click();
  } else {
    console.log('Element not found.');
  }

  await browser.close();
})();

Explanation

  • pierce selector syntax:
    Use pierce: as a prefix before the CSS selector to search within the shadow DOM.

  • Why use pierce?
    Regular CSS selectors in Puppeteer can't directly access elements inside a shadow tree. Without pierce, you would need to manually traverse shadow roots, which can be cumbersome.


When to Use It?

  • Shadow DOM elements: If a website uses web components or encapsulated DOM structures, such as custom elements with shadow DOM.
  • Avoid manual traversal: Reduces the need for cumbersome JavaScript like element.shadowRoot.querySelector().

Alternative: Recursive Shadow DOM Search

If the pierce selector isn't available, you can manually access shadow DOM elements like this:

const shadowHost = await page.$('#host-element');
const shadowRoot = await shadowHost.evaluateHandle(el => el.shadowRoot);
const shadowElement = await shadowRoot.$('#shadow-element');

This is more verbose, but it achieves the same goal if pierce support is unavailable or experimental in your Puppeteer version【19†source】【20†source】.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

HTML Inline divisions at one row by Tailwind

Boilerplate for typescript server programing

가속도 & 속도

Gradle multi-module project

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

CDPEvents in puppeteer

Sparse encoder

Reactjs datetime range picker