-
-
Save double-beep/c4d4ec3866e5e54ae514c0aab60af242 to your computer and use it in GitHub Desktop.
A utility function, for Greasemonkey scripts, that detects and handles AJAXed content.
This file contains hidden or 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
/* waitForKeyElements(): The improved utility function for userscripts - now with MutationObservers and no jQuery! | |
Usage example: | |
waitForKeyElements( | |
'div.comments', | |
element => console.log('Look! A new element appeared!', element) | |
); | |
// ----------------------------------------------------------------- | |
waitForKeyElements( | |
'ul#list', | |
callbackFunction, | |
false | |
); | |
function callbackFunction(node) { | |
node.innerText = 'Text changed with waitForKeyElements()'; | |
} | |
*/ | |
/** | |
* waitForKeyElements | |
* @param {string} selector Required: The selector string that specifies the desired element(s). | |
* @param {Function} callback Required: The code to run when elements are found. It is passed an element to the matched element. | |
* @param {boolean} bWaitOnce Optional: If false, will continue to scan for new elements even after the first match is found (default is true). | |
*/ | |
function waitForKeyElements(selector, callback, bWaitOnce = true) { | |
const elements = document.querySelectorAll(selector); | |
if (elements) { | |
// if the elements already exist, then call the function passed | |
elements.forEach(element => callback(element)); | |
} | |
const observer = new MutationObserver(mutations => { | |
mutations | |
.filter(({ addedNodes }) => addedNodes.length) // keep only newly added elements | |
.forEach(({ addedNodes }) => { | |
[...addedNodes] | |
.filter(element => element?.matches?.(selector)) | |
.forEach(element => callback(element, observer)); | |
// respect bWaitOnce | |
if (bWaitOnce) observer.disconnect(); | |
}); | |
}); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment