在此页面上,我希望我的 Chrome 扩展程序等待所有页面元素完全加载。我怎么做?第一个
MutationObserver
有效,第二个无效。
var waitForBody = function() {
return new Promise(resolve => {
if (document.documentElement.getElementsByTagName('body')) {
return resolve(document.documentElement.getElementsByTagName('body'));
}
const observer = new MutationObserver(mutations => {
if (document.documentElement.getElementsByTagName('body')) {
resolve(document.documentElement.getElementsByTagName('body'));
observer.disconnect();
}
});
observer.observe(document.documentElement);
});
}
var waitById = function(elmId) {
return new Promise(resolve => {
if (document.getElementById(elmId)) {
return resolve(document.getElementById(elmId));
}
const observer = new MutationObserver(mutations => {
if (document.getElementById(elmId)) {
resolve(document.getElementById(elmId));
observer.disconnect();
}
});
observer.observe(document.body, {childList: true});
});
}
waitForBody().then((elm) => {
console.log('elm is ready');
console.log(document.getElementById('#xt-popover'));
waitById('#xt-popover').then((elm2) => {
console.log('elm2 is ready');
});
});
# elm is ready
# null