簡體   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