8

I'm having difficulties with actions on elements in shadowroot in my test context. Lets say I have a web component <my-component /> and it contains a button <input id="my-button" type="submit" />

From console in chrome, I can do the following:

document.getElementsByTagName('my-component')[0].shadowRoot.querySelector('#my-button').click()

Im struggling doing the same with puppeteer.

  it('should click the button', async () => {
    await page.goto(`https://localhost:${port}`, {
      waitUntil: ['networkidle0', 'load'],
    });

    await page.$eval('my-component', (el: Element) => {
      el.shadowRoot.querySelector('#my-button').click();
    });
  });

Clicking the button should fire an http request to my server that retrieves some data which I then want to assert on in the dom. The request never fires. Suggestions?

R. Gulbrandsen
  • 3,648
  • 1
  • 22
  • 35

2 Answers2

13

According to this comment from the Puppeteer Team the right way is to use JS path:

In Chrome 72 (current Canary) we introduced a new option - "Copy JS Path", located right next to the "Copy Selector" option:

aaa

Example using JS path:

    it('should click the button', async () => {
      await page.goto(`https://localhost:${port}`, {
        waitUntil: ['networkidle0', 'load'],
      });
    
      const button = await (await page.evaluateHandle(`<JS-path-here>`)).asElement();
      button.click();
    });
Daniel
  • 162
  • 1
  • 6
  • Downvoted because as a developer this answer is not useful – user2965205 Apr 05 '21 at 06:56
  • 2
    Thanks, this did expose the shadow DOM. Now you can also use 'pierce' like so `const the_elem = await elem_parent.$('pierce/div.the_elem');` – Anthony Aug 14 '22 at 23:26
  • 1
    The page I'm trying to copy the `JS Path` has the option greyed out on Chrome. – Vinny Oct 08 '22 at 20:45
  • This just returns: `Evaluation failed: TypeError: Cannot read properties of null (reading 'shadowRoot')` for me. :( – q. wellington Mar 13 '23 at 13:15
  • `button.click();` should be `await button.click();`. OP hasn't shared a [mcve], but what they're doing looks OK. I don't recommend using [browser-generated selectors](https://serpapi.com/blog/puppeteer-antipatterns/#misusing-developer-tools-generated-selectors). See also [this post](https://stackoverflow.com/a/68540701/6243352) on working with shadow roots in Puppeteer, which has links to many other resources. `pierce/` is a great suggestion. – ggorlen Apr 14 '23 at 01:54
1

This issue is solved with P selectors in Puppetteer.

In this case you could use page.click('>>> #my-button'). The >>> Allow you to select stuff in shadowRoots.

I know this issue is old, but I needed this and this issue still pops up on searches.

Remco Vaes
  • 41
  • 3