WaitForKeyElement

Waits for an element using the MutationObserver API

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/523012/1519437/WaitForKeyElement.js

  1. // ==UserScript==
  2. // @name WaitForKeyElement
  3. // @namespace Violentmonkey Scripts
  4. // @version 1.1
  5. // @description Waits for an element using the MutationObserver API
  6. // @author PaywallDespiser
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. /**
  11. * Waits for a element of a given selector.
  12. *
  13. * @param {string} selector
  14. * @param {Element} [target=document.body]
  15. * @returns {Promise<Element>}
  16. */
  17. function waitForKeyElement(selector, target = document.body) {
  18. return new Promise((resolve) => {
  19. {
  20. const element = target.querySelector(selector);
  21. if (element) {
  22. return resolve(element);
  23. }
  24. }
  25.  
  26. const observer = new MutationObserver((mutations) => {
  27. for (const mutation of mutations) {
  28. for (const node of mutation.addedNodes) {
  29. if (!(node instanceof HTMLElement)) continue;
  30.  
  31. if (node.matches(selector)) {
  32. observer.disconnect();
  33. resolve(node);
  34. return;
  35. }
  36. const childElement = node.querySelector(selector);
  37. if (childElement) {
  38. observer.disconnect();
  39. resolve(childElement);
  40. return;
  41. }
  42. }
  43. }
  44. });
  45.  
  46. observer.observe(target, {
  47. childList: true,
  48. subtree: true,
  49. attributes: false,
  50. characterData: false,
  51. });
  52. });
  53. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址