Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add observeAttributes parameter to waitForChildAdd() #145

Merged
merged 1 commit into from
Mar 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/userScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import './ui.js';
/** @type {HTMLVideoElement} */
const video = await waitForChildAdd(
document.body,
(node) => node instanceof HTMLVideoElement
(node) => node instanceof HTMLVideoElement,
false
);

const playerCtrlObs = new MutationObserver(() => {
Expand Down
30 changes: 22 additions & 8 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,24 @@ export function handleLaunch(params) {
}

/**
* Wait for a child element to be added that holds true for a predicate
* @template T
* @param {Element} parent
* @param {(node: Node) => node is T} predicate
* @param {AbortSignal=} abortSignal
* @return {Promise<T>}
* Wait for a child element to be added for which a predicate is true.
*
* When `observeAttributes` is false, the predicate is checked only when a node
* is first added. If you want the predicate to run every time an attribute is
* modified, set `observeAttributes` to true.
* @template {Node} T
* @param {Element} parent Root of tree to watch
* @param {(node: Node) => node is T} predicate Function that checks whether its argument is the desired element
* @param {boolean} observeAttributes Also run predicate on attribute changes
* @param {AbortSignal=} abortSignal Signal that can be used to stop waiting
* @return {Promise<T>} Matched element
*/
export async function waitForChildAdd(parent, predicate, abortSignal) {
export async function waitForChildAdd(
parent,
predicate,
observeAttributes,
abortSignal
) {
return new Promise((resolve, reject) => {
const obs = new MutationObserver((mutations) => {
for (const mut of mutations) {
Expand Down Expand Up @@ -128,6 +138,10 @@ export async function waitForChildAdd(parent, predicate, abortSignal) {
});
}

obs.observe(parent, { subtree: true, attributes: true, childList: true });
obs.observe(parent, {
subtree: true,
attributes: observeAttributes,
childList: true
});
});
}