Wait For Selector

Waits for elements

当前为 2021-10-22 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/432418/981655/Wait%20For%20Selector.js

  1. // ==UserScript==
  2. // @name Wait For Selector
  3. // @namespace http://tampermonkey.net/
  4. // @description Waits for elements
  5. // @author Kumirei
  6. // @include *community.wanikani.com*
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. ;(function ($, wfs) {
  11. let version = '0.1.1'
  12.  
  13. // Create new observer on body to monitor all DOM changes
  14. let observer = new MutationObserver(mutationHandler)
  15. observer.observe(document.getElementsByTagName('html')[0], { childList: true, subtree: true })
  16.  
  17. // Interface for interacting with the library
  18. let interface = {
  19. version,
  20. observer: observer,
  21. wait: waitForSelector,
  22. unwait: unwaitID,
  23. waits: {},
  24. waitsByID: {},
  25. nextID: 0,
  26. }
  27.  
  28. // Start
  29. installInterface()
  30.  
  31. // Creates a new entry to search for whenever a new element is added to the DOM
  32. function waitForSelector(selector, callback) {
  33. if (!interface.waits[selector]) interface.waits[selector] = {}
  34. interface.waits[selector][interface.nextID] = callback
  35. interface.waitsByID[interface.nextID] = selector
  36. search(selector, true)
  37. return interface.nextID++
  38. }
  39.  
  40. // Deletes a previously registered selector
  41. function unwaitID(ID) {
  42. delete interface.waits[interface.waitsByID[ID]][ID]
  43. delete interface.waitsByID[ID]
  44. }
  45.  
  46. // Makes sure that the public interface is the newest version and the same as the local one
  47. function installInterface() {
  48. if (!wfs) window.wfs = interface
  49. else if (wfs.version < interface.version) {
  50. wfs.version = interface.version
  51. wfs.observer.disconnect()
  52. wfs.observer = interface.observer
  53. wfs.wait = interface.wait
  54. wfs.unwait = interface.unwait
  55. }
  56. interface = wfs || interface
  57. }
  58.  
  59. // Waits until there has been more than 300 ms between mutations and then checks for new elements
  60. let lastMutationDate = 0 // Epoch of last mutation event
  61. function mutationHandler(mutations) {
  62. let duration = Date.now() - lastMutationDate
  63. lastMutationDate = Date.now()
  64. if (duration > 300) {
  65. for (let selector in interface.waits) search(selector)
  66. }
  67. }
  68.  
  69. // Searches for the selector and calls the callback on the found elements
  70. function search(selector, all = false) {
  71. $(selector).each((i, e) => {
  72. let callbacks = Object.values(interface.waits[selector])
  73. if (all || !e.WFSFound || e.WFSFound == lastMutationDate) {
  74. for (let callback of callbacks) callback(e)
  75. e.WFSFound = lastMutationDate
  76. }
  77. })
  78. }
  79. })(window.jQuery, window.wfs)