1

I'd like my Chrome extension to insert some text in spans which are constantly updated as you scroll. On this page, I can get all the elements I need with this code:

var agoEls = [...document.querySelectorAll("#metadata-line span:nth-child(4)")];

How do I run the code so that it starts working after the first span item appears?

How to get new elements that appear after the page scrolls and run code for them too as they appear?

I tried MutationObserver.observe(), but I don't know how best to use it in this case. It seems impossible to use it with high performance. I can wait for a body with little performance overhead:

function waitForBody() {
  return new Promise(resolve => {
    if (document.documentElement.getElementsByTagName("body")) {
      return resolve(document.documentElement.getElementsByTagName("body"));
    }

    const observer = new MutationObserver(mutations => {
      if (document.documentElement.getElementsByTagName("body")) {
        resolve(document.documentElement.getElementsByTagName("body"));
        observer.disconnect();
      }
    });

    observer.observe(document.documentElement);
  });
}

waitForBody().then((elm) => {
  console.log('Element is ready');
});

But then, as suggested here, I have to use subtree: true and collect all changes for all elements in the whole giant tree:

enter image description here

Maybe I'm doing something wrong and there's a better way?

senops
  • 31
  • 3
  • Try finding a `yt` event for your use case as [shown here](https://stackoverflow.com/a/34100952), then if you're lucky the elements will be there when such an event is triggered, otherwise find the event that is triggered just before the change and temporarily enable a global observer. – wOxxOm Feb 25 '23 at 17:25
  • @wOxxOm Could you elaborate on what I need to do? I only have these `yt` events: `yt-guide-close yt-guide-show yt-guide-toggle yt-navigate-cache yt-navigate-finish yt-navigate-start yt-page-type-changed yt-toggle-button`. How do I know where the elements I need are located? – senops Feb 25 '23 at 19:35

0 Answers0