How to interact with shadow DOM elements in Puppeteer?

To interact with shadow DOM elements in Puppeteer, you can use the evaluate function to execute JavaScript code inside the page context. Here are the steps to interact with shadow DOM elements in Puppeteer:

  1. First, identify the shadow DOM element you want to interact with using the browser's DevTools or by inspecting the page structure.

  2. Use Puppeteer to navigate to the page where the shadow DOM element is located.

  3. Use the evaluate function to select and interact with the shadow DOM element. Here's an example of how to click on a button inside a shadow DOM element:

await page.evaluate(() => { // Select the shadow DOM element const shadowRoot = document.querySelector('your-shadow-root-selector').shadowRoot; // Select the button inside the shadow DOM element const button = shadowRoot.querySelector('your-button-selector'); // Click on the button button.click(); });
  1. You can also extract information from shadow DOM elements using the evaluate function. For example, if you want to get the text content of a span inside a shadow DOM element:
const textContent = await page.evaluate(() => { const shadowRoot = document.querySelector('your-shadow-root-selector').shadowRoot; const span = shadowRoot.querySelector('your-span-selector'); return span.textContent; }); console.log(textContent);

By using the evaluate function in Puppeteer, you can interact with and extract information from shadow DOM elements in the browser.