fix: untilElementLoaded()
when element already exists
This commit is contained in:
parent
36d9211dce
commit
6e284ce259
1 changed files with 12 additions and 12 deletions
24
index.js
24
index.js
|
@ -1,11 +1,10 @@
|
||||||
// ==UserScript==
|
// ==UserScript==
|
||||||
// @name sup-ytsync
|
// @name sup-ytsync
|
||||||
// @namespace http://tampermonkey.net/
|
// @namespace https://forgejo.sup39.dev/sup39/sup-ytsync/
|
||||||
// @version 0.1.0
|
// @version 2024-01-30
|
||||||
// @description sup39
|
// @description A script to sync Youtube video progress with others via MQTT
|
||||||
// @author sup39
|
// @author sup39
|
||||||
// @match https://www.youtube.com/watch*
|
// @match https://www.youtube.com/watch*
|
||||||
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
|
|
||||||
// @grant none
|
// @grant none
|
||||||
// ==/UserScript==
|
// ==/UserScript==
|
||||||
|
|
||||||
|
@ -162,24 +161,25 @@
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Based on https://stackoverflow.com/a/61511955 by Yong Wang (2020)
|
|
||||||
/**
|
/**
|
||||||
* @param {string} selector
|
* @param {string} selector
|
||||||
|
* @param {Element} root
|
||||||
* @returns {Promise<Element>}
|
* @returns {Promise<Element>}
|
||||||
*/
|
*/
|
||||||
const untilElementLoaded = selector => new Promise(resolve => {
|
// https://stackoverflow.com/a/61511955
|
||||||
const elm = document.querySelector(selector);
|
const untilElementLoaded = (selector, root=document.body) => new Promise(resolve => {
|
||||||
if (elm != null) return elm;
|
// 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 observer = new MutationObserver(() => {
|
||||||
const elm = document.querySelector(selector);
|
const elm = root.querySelector(selector);
|
||||||
if (elm != null) {
|
if (elm != null) {
|
||||||
observer.disconnect();
|
observer.disconnect();
|
||||||
resolve(elm);
|
resolve(elm);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
observer.observe(root, {
|
||||||
observer.observe(document.body, {
|
|
||||||
childList: true,
|
childList: true,
|
||||||
subtree: true
|
subtree: true
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue