Last active
November 9, 2021 09:43
-
-
Save noahcoad/32aefee585901acecdd69617d1082462 to your computer and use it in GitHub Desktop.
Utility function for Tampermonkey and Greasemonkey scripts to detect and handle AJAX elements and single page apps, waiting until elements exist and become visible
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
// | |
// Description | |
// whenVisible(): a utility function for Tampermonkey and Greasemonkey | |
// scripts to detect and handle AJAX elements and single | |
// page apps, waiting until elements exist and become visible | |
// | |
// Created | |
// 2021-10-01 by Noah Coad http://coad.net | |
// | |
// Usage Example | |
// whenVisible("button[type=username]", 0, x => x.value = "noahcoad") | |
// | |
// Credits | |
// thanks to BrockA for his waitForKeyElement() func which inspired this | |
// https://gist.github.com/BrockA/2625891 | |
// | |
// Gist | |
// https://gist.github.com/noahcoad/32aefee585901acecdd69617d1082462 | |
// | |
function whenVisible(sel, func, idx = 0) { | |
// sel = css selector, such as "button[type=username]" | |
// func = function to call, passes the element found | |
// idx = index of the element to find (if not the first element) | |
var intv = setInterval(function() { | |
var elems = document.querySelectorAll(sel); | |
// if (elems.length < 1) { return false; } | |
if (elems.length > idx) { | |
if (!(window.getComputedStyle(elems[idx]).display === 'none')) { | |
// when element is found, and visibile, clear the interval. | |
clearInterval(intv); | |
// call function | |
func(elems[idx]); | |
} | |
} | |
else return false; | |
}, 200); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment