Created
October 26, 2021 08:37
-
-
Save MarcelloTheArcane/4e1d9458929d48fa1b962b88e400ccdc to your computer and use it in GitHub Desktop.
Wait for an element to be inserted to the DOM. It tries a query selector on all mutation events.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This assumes that the selector will eventually appear - it'll hang indefinitely otherwise. | |
// You may need a slight delay after this returns, for the element to have its event handlers attached. | |
async function waitForElementToExist (selector) { | |
return new Promise(resolve => { | |
const observer = new MutationObserver(() => { | |
const element = document.querySelector(selector) | |
if (element) { | |
observer.disconnect() | |
return resolve(element) | |
} | |
}) | |
observer.observe(document, { | |
childList: true, | |
subtree: true, | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment