Last active
October 21, 2024 13:52
-
-
Save mattzeunert/c639ff38c2757cb610e8ce71e7525419 to your computer and use it in GitHub Desktop.
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
var waitFor = async function waitFor(conditionFn, { timeout = 15000, checkInterval = 25, debugString = null, } = {}) { | |
if (typeof conditionFn !== "function") { | |
throw Error("waitFor condition argument isn't a function. Did you mean waitForElement?"); | |
} | |
if (!debugString) { | |
debugString = conditionFn.toString(); | |
} | |
let startedAt = new Date(); | |
let conditionResult = await conditionFn(); | |
while (!conditionResult) { | |
await new Promise((resolve) => setTimeout(resolve, checkInterval)); | |
if (new Date().valueOf() - startedAt.valueOf() > timeout) { | |
throw Error(`Wait for condition timed out after ${timeout} ms: ${debugString}`); | |
} | |
conditionResult = await conditionFn(); | |
} | |
return conditionResult; | |
}; | |
var waitForElement = function waitForElement(selector, { containingText = null, timeout = 15000, checkInterval = 25, } = {}) { | |
if (typeof selector !== "string") { | |
throw Error("waitForElement selector isn't a string: " + selector); | |
} | |
let debugString = `waitForElement "${selector}"`; | |
if (containingText) { | |
debugString += ` (containing text: "${containingText}")`; | |
} | |
return waitFor(() => { | |
const els = document.querySelectorAll(selector); | |
if (els.length > 0) { | |
if (containingText) { | |
let matchingEl = Array.from(els).find((el) => (el.textContent || "").includes(containingText)); | |
if (matchingEl) { | |
return matchingEl; | |
} | |
} | |
else { | |
return els[0]; | |
} | |
} | |
}, { timeout, checkInterval, debugString }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment