Wait For Selector

Waits for elements

当前为 2021-09-27 提交的版本,查看 最新版本

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

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