简体   繁体   中英

Identify page finished loading content after page was already finished loading

I need write a browser plugin for Chrome where I want to manipulate certain elements. Manipulating the content is not an issue but the page I want to manipulate loads additional content after the page was already done loading.

So my script changes the content but once the page loads the additional content it rebuilds the content and overwrites my changes again.

How can I track those changes or additional loading elements?

Thanks

I would recommend either using a setInterval which would allow you to overwrite any changes made after the additional content is loaded. Or a MutationObserver which would allow you watch all incoming changes and make updates accordingly.

setInterval Example:

setInterval(() => {
  // Check to see if your modification is on the page
  // If not then re-add it
  if (!document.body.innerHTML.includes('<div id="target">')) {
    // Call your function to modify the content
    yourFunction();
  }
  // Run every second
}, 1000);

MutationObserver Example:

const observeMutations = (targetNode, baseElm, addedElm, cb) => {
  const observer = new MutationObserver((mutationsList) => {
    // Iterate through each incoming change to the DOM
    for (const mutation of mutationsList) {
      const HTML = String(mutation.target.innerHTML);
      // Feel free to modify this to fit your use case
      // Call function if the base element exists, but your modification does not
      if (HTML.includes(baseElm) && !HTML.includes(addedElm)) {
        // Call your function to apply to the page
        cb();
        break;
      }
    }
  });

  // Configuration options:
  // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
  const options = {
    attributes: true,
    childList: true,
    subtree: true,
  };

  observer.observe(targetNode, options);

  // Disconnect observer on a timer for slow loading elements
  setTimeout(() => observer.disconnect(), 15000);
};

observeMutations(<your inputs>)

References

setInverval: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval MutationObserver: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM