在页面已完成加载之后标识已完成加载的页面内容



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

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

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

感谢

我建议使用setInterval,这将允许您覆盖加载附加内容后所做的任何更改。或者MutationObserver,它将允许您监视所有传入的更改并相应地进行更新。

setInterval示例:

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

突变观察者示例:

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突变观察者:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

最新更新