🏠 Home 

WaitForKeyElement

Waits for an element using the MutationObserver API

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greasyfork.org/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. * Waits for a element of a given selector.
  11. *
  12. * @param {string} selector
  13. * @param {Element} [target=document.body]
  14. * @returns {Promise<Element>}
  15. */
  16. function waitForKeyElement(selector, target = document.body) {
  17. return new Promise((resolve) => {
  18. {
  19. const element = target.querySelector(selector);
  20. if (element) {
  21. return resolve(element);
  22. }
  23. }
  24. const observer = new MutationObserver((mutations) => {
  25. for (const mutation of mutations) {
  26. for (const node of mutation.addedNodes) {
  27. if (!(node instanceof HTMLElement)) continue;
  28. if (node.matches(selector)) {
  29. observer.disconnect();
  30. resolve(node);
  31. return;
  32. }
  33. const childElement = node.querySelector(selector);
  34. if (childElement) {
  35. observer.disconnect();
  36. resolve(childElement);
  37. return;
  38. }
  39. }
  40. }
  41. });
  42. observer.observe(target, {
  43. childList: true,
  44. subtree: true,
  45. attributes: false,
  46. characterData: false,
  47. });
  48. });
  49. }