繁体   English   中英

在页面已经完成加载后识别页面完成加载内容

[英]Identify page finished loading content after page was already finished loading

我需要为 Chrome 编写一个浏览器插件,我想在其中操作某些元素。 操作内容不是问题,但我要操作的页面会在页面加载完成后加载其他内容。

因此,我的脚本更改了内容,但是一旦页面加载了其他内容,它就会重新构建内容并再次覆盖我的更改。

如何跟踪这些更改或其他加载元素?

谢谢

我建议使用setInterval ,它允许您覆盖加载附加内容后所做的任何更改。 或者一个MutationObserver ,它可以让你观察所有传入的变化并相应地进行更新。

设置间隔示例:

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示例:

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>)

参考

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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