Simple WaitForKeyElement

Library that Exports my simplified vanilla JS version of WaitForKeyElement, which is a simple async function that returns a Promise that resolves to an element by a given selector, when that element is found

目前为 2024-10-01 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/511024/1457630/Simple%20WaitForKeyElement.js

  1. // ==UserScript==
  2. // @name Simple WaitForKeyElement
  3. // @license MIT
  4. // @namespace 1N07
  5. // @match *://*/*
  6. // @version 1.0
  7. // @author 1N07
  8. // @description Library that Exports my simplified vanilla JS version of WaitForKeyElement, which is a simple async function that returns a Promise that resolves to an element by a given selector, when that element is found
  9. // ==/UserScript==
  10.  
  11. async function WaitForKeyElement(selector, timeout) {
  12. return new Promise((resolve, reject) => {
  13. let el = document.querySelector(selector);
  14.  
  15. if (el) {
  16. resolve(el);
  17. return;
  18. }
  19.  
  20. new MutationObserver((mutationRecords, observer) => {
  21. el = document.querySelector(selector);
  22. if (el) {
  23. resolve(el);
  24. observer.disconnect();
  25. }
  26. }).observe(document.documentElement, { childList: true, subtree: true });
  27.  
  28. if (timeout) {
  29. setTimeout(() => {
  30. reject(null);
  31. }, timeout);
  32. }
  33. });
  34. }