javascriptgoogle-chrome-devtoolsgoogle-chrome-console

send clicks to "generated source/computed html" buttons via Chrome Dev Tools console


I have to review a large number of videos on a webpage (screenshot below). The videos are partially hidden. And to view each video, I have to click the more button one by one (as shown in the image below). enter image description here

There are often 40 videos per page. Constantly scrolling and clicking the more button over and over again is tedious, and if I keep doing it I think I'll have a repetitive stress injury.

So, I thought I'd use Chrome Dev Tools' console to identify the buttons and send them clicks all in one batch process.

I am able to find the more buttons using the inspect tool in Chrome Dev Tools, like so: enter image description here

The more button's DOM-tree breadcrumb via inspect (please CLICK to enlarge, there are two image parts below):

enter image description here

enter image description here

The more button markup code looks like this:

<button class="d2l-label-text" type="button">
    <d2l-icon class="d2l-button-subtle-icon" icon="d2l-tier1:chevron-down" dir="ltr"></d2l-icon>
    <span class="d2l-button-subtle-content"><!---->more<!----></span>
    <slot></slot>
</button>

and the more button's class is d2l-label-text

I thought I'd do something like this in the console:

> let allbuttonsArray = document.getElementsByClassName("d2l-label-text");

  for (let eachbutton of allbuttonsArray) {
    eachbutton.click();
  }

However, it turns out that document.getElementsByClassName("d2l-label-text") is not grabbing anything. The length of the result array is 0.

I tried to play around with some other selectors and discovered that the console is not grabbing from the generated source/computed html, it's only grabbing tags/elements that are there in the source (the original source that can be obtained via right-click, view source).

My Question: What am I doing wrong? How do I get the console to grab the generated source/computed html more buttons?


Solution

  • As can be seen on the screenshots, the element is inside a ShadowRoot which means it's not accessible directly from the main document.

    To find such an element you'll have to access the ShadowRoot chain recursively.
    In your case there are two elements in this chain.

    for (const more of document.querySelectorAll('d2l-more-less')) {
      for (const buttonSubtle of more.shadowRoot.querySelectorAll('d2l-button-subtle')) {
        const btn = buttonSubtle.shadowRoot.querySelector('button');
        if (btn) btn.dispatchEvent(new MouseEvent('click', {bubbles: true}));
      }
    }
    

    In case the shadowRoot is created by the page in 'closed' mode you'll probably have to hook Element.prototype.attachShadow in page context script.