From 6e284ce2590bc625ab504808e96f8c951181bed5 Mon Sep 17 00:00:00 2001 From: sup39 Date: Tue, 30 Jan 2024 08:38:54 +0900 Subject: [PATCH] fix: `untilElementLoaded()` when element already exists --- index.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 3565d9c..72644fd 100644 --- a/index.js +++ b/index.js @@ -1,11 +1,10 @@ // ==UserScript== // @name sup-ytsync -// @namespace http://tampermonkey.net/ -// @version 0.1.0 -// @description sup39 +// @namespace https://forgejo.sup39.dev/sup39/sup-ytsync/ +// @version 2024-01-30 +// @description A script to sync Youtube video progress with others via MQTT // @author sup39 // @match https://www.youtube.com/watch* -// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com // @grant none // ==/UserScript== @@ -162,24 +161,25 @@ }); }); - // Based on https://stackoverflow.com/a/61511955 by Yong Wang (2020) /** * @param {string} selector + * @param {Element} root * @returns {Promise} */ - const untilElementLoaded = selector => new Promise(resolve => { - const elm = document.querySelector(selector); - if (elm != null) return elm; - + // https://stackoverflow.com/a/61511955 + const untilElementLoaded = (selector, root=document.body) => new Promise(resolve => { + // resolve immediately if element already exists + const elm = root.querySelector(selector); + if (elm != null) return resolve(elm); + // observe root until element presents const observer = new MutationObserver(() => { - const elm = document.querySelector(selector); + const elm = root.querySelector(selector); if (elm != null) { observer.disconnect(); resolve(elm); } }); - - observer.observe(document.body, { + observer.observe(root, { childList: true, subtree: true });