fix: untilElementLoaded() when element already exists

This commit is contained in:
sup39 2024-01-30 08:38:54 +09:00
parent 36d9211dce
commit 6e284ce259
Signed by: sup39
GPG key ID: 111C00916C1641E5

View file

@ -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<Element>}
*/
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
});