function awaitElement(selector) {
return awaitPredicate(selector, _ => true);
}
function awaitPredicate(selector, predicate) {
return new Promise((resolve, _reject) => {
for (const el of document.querySelectorAll(selector)) {
if (predicate(el)) {
resolve(el);
return;
}
}
// Create a MutationObserver to listen for changes
const observer = new MutationObserver((_mutations, obs) => {
// You could search just inside _mutations instead of the entire DOM.
// Efficiency will depend primarily on how precise your selector is.
for (const el of document.querySelectorAll(selector)) {
if (predicate(el)) {
resolve(el);
obs.disconnect(); // Don't forget to disconnect the observer!
break;
}
}
});
// Start observing the document
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
});
}Oh the horrible things I do with Instagram...
I just try and get LLMs to do it for me because I'm lazy, and they like to use setInterval instead of mutationObservers and if it works, I just live with the inefficiency.