I'm trying to get all the images on the page to load (from the chrome extension side) and then execute some code on those images, problem is sometimes sites load images lazily (e.g. when the user scrolls down to them).

Is there any way to make sure all of them are loaded? I tried scrolling down to the bottom of the window but that won't work with pagination.

export function imagesHaveLoaded() {
  return Array.from(document.querySelectorAll("img")).every(img => img.complete && img.naturalWidth);
}

return Promise.resolve()
      .then(() => (document.scrollingElement.scrollTop = bottom))
      .then(
        new Promise((resolve, reject) => {
          let wait = setTimeout(() => {
            clearTimeout(wait);
            resolve();
          }, 400);
        })
      )
      .then(() => {
        console.log(document.scrollingElement.scrollTop);
        document.scrollingElement.scrollTop = currentScroll;
      })
      .then(
        new Promise((resolve, reject) => {
          let wait = setTimeout(() => {
            clearTimeout(wait);
            resolve();
          }, 400);
        })
      )
      .then(until(imagesHaveLoaded, 2000))
      .then(Promise.all(promises));

It loads the lazy loading images but if there are more of them that are lazy loaded it won't work (I need the image itself to be loaded not the url so I can read it's data)

1 Answers

1
Adam Soto On

if you wanna catch every new image loaded to the page you can use a MutationObserver like this code snippet:

    const targetNode = document.getElementById("root");

    // Options for the observer (which mutations to observe)
    let config = { attributes: true, childList: true, subtree: true };

    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
        for(let mutation of mutationsList) {
            if (mutation.addedNodes[0].tagName==="IMG") {
                console.log("New Image added in DOM!");
            }   
        }
    };

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);

    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);