UserscriptAPIWait

https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI

As of 2021-09-06. See the latest version.

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.greatest.deepsurf.us/scripts/432002/967890/UserscriptAPIWait.js

  1. /**
  2. * UserscriptAPIWait
  3. *
  4. * 依赖于 `UserscriptAPI`,`UserscriptAPITool`。
  5. * @version 1.0.0.20210906
  6. * @author Laster2800
  7. * @see {@link https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI UserscriptAPI}
  8. */
  9. class UserscriptAPIWait {
  10. /**
  11. * @param {UserscriptAPI} api `UserscriptAPI`
  12. */
  13. constructor(api) {
  14. this.api = api
  15. }
  16.  
  17. /**
  18. * 在条件达成后执行操作
  19. *
  20. * 当条件达成后,如果不存在终止条件,那么直接执行 `callback(result)`。
  21. *
  22. * 当条件达成后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否达成终止条件,称为终止条件的二次判断。如果在此期间,终止条件通过,则表示依然不达成条件,故执行 `onStop()` 而非 `callback(result)`。如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  23. *
  24. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  25. * @param {() => (* | Promise)} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  26. * @param {(result: *) => void} [options.callback] 当达成条件时执行 `callback(result)`
  27. * @param {number} [options.interval] 检测时间间隔
  28. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  29. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  30. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  31. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  32. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  33. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  34. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  35. * @param {(e: Error) => void} [options.onError] 条件检测过程中发生错误时执行 `onError(e)`
  36. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  37. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  38. * @returns {() => boolean} 执行后终止检测的函数
  39. */
  40. executeAfterConditionPassed(options) {
  41. options = {
  42. ...this.api.options.wait.condition,
  43. ...options,
  44. }
  45. let stop = false
  46. let endTime = null
  47. if (options.timeout == 0) {
  48. endTime = 0
  49. } else {
  50. endTime = Math.max(new Date().getTime() + options.timeout - options.timePadding, 1)
  51. }
  52. const task = async () => {
  53. if (stop) return
  54. let result = null
  55. try {
  56. result = await options.condition()
  57. } catch (e) {
  58. options.onError?.(e)
  59. if (options.stopOnError) {
  60. stop = true
  61. }
  62. }
  63. if (stop) return
  64. const stopResult = await options.stopCondition?.()
  65. if (stopResult) {
  66. stop = true
  67. options.onStop?.()
  68. } else if (endTime !== 0 && new Date().getTime() > endTime) {
  69. if (options.stopOnTimeout) {
  70. stop = true
  71. } else {
  72. endTime = 0
  73. }
  74. options.onTimeout?.()
  75. } else if (result) {
  76. stop = true
  77. if (options.stopCondition && options.stopTimeout > 0) {
  78. this.executeAfterConditionPassed({
  79. condition: options.stopCondition,
  80. callback: options.onStop,
  81. interval: options.stopInterval,
  82. timeout: options.stopTimeout,
  83. onTimeout: () => options.callback(result)
  84. })
  85. } else {
  86. options.callback(result)
  87. }
  88. }
  89. if (!stop) {
  90. setTimeout(task, options.interval)
  91. }
  92. }
  93. setTimeout(async () => {
  94. if (stop) return
  95. await task()
  96. if (stop) return
  97. setTimeout(task, options.interval)
  98. }, options.timePadding)
  99. return function() {
  100. stop = true
  101. }
  102. }
  103.  
  104. /**
  105. * 在元素加载完成后执行操作
  106. *
  107. * ```plaintext
  108. * +──────────+────────+───────────────────────────────────+
  109. * multiple | repeat | 说明
  110. * +──────────+────────+───────────────────────────────────+
  111. * false | false | 查找第一个匹配元素,然后终止查找
  112. * true | false | 查找所有匹配元素,然后终止查找
  113. * false | true | 查找最后一个非标记匹配元素,并标记所有
  114. * | | 匹配元素,然后继续监听元素插入
  115. * true | true | 查找所有非标记匹配元素,并标记所有匹配
  116. * | | 元素,然后继续监听元素插入
  117. * +────────────+──────────+───────────────────────────────────+
  118. * ```
  119. *
  120. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  121. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  122. * @param {HTMLElement} [options.base] 基元素
  123. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  124. * @param {(element: HTMLElement) => void} [options.callback] 当 `element` 加载成功时执行 `callback(element)`
  125. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  126. * @param {boolean} [options.multiple] 若一次检测到多个目标元素,是否在所有元素上执行回调函数(否则只处理第一个结果)
  127. * @param {boolean} [options.repeat] `element` 加载成功后是否继续检测
  128. * @param {number} [options.throttleWait] 检测节流时间(非准确)
  129. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  130. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  131. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  132. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  133. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  134. * @param {(e: Error) => void} [options.onError] 检测过程中发生错误时执行 `onError(e)`
  135. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  136. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  137. * @returns {() => boolean} 执行后终止检测的函数
  138. */
  139. executeAfterElementLoaded(options) {
  140. const api = this.api
  141. options = {
  142. ...api.options.wait.element,
  143. ...options,
  144. }
  145.  
  146. let loaded = false
  147. let stopped = false
  148. let tid = null // background timer id
  149.  
  150. let excluded = null
  151. if (options.exclude) {
  152. excluded = new WeakSet(options.exclude)
  153. } else if (options.repeat) {
  154. excluded = new WeakSet()
  155. }
  156. const valid = el => !(excluded?.has(el))
  157.  
  158. const stop = () => {
  159. if (!stopped) {
  160. stopped = true
  161. ob.disconnect()
  162. if (tid) {
  163. clearTimeout(tid)
  164. tid = null
  165. }
  166. }
  167. }
  168.  
  169. const singleTask = el => {
  170. let success = false
  171. try {
  172. if (valid(el)) {
  173. success = true // success 指查找成功,回调出错不影响
  174. options.repeat && excluded.add(el)
  175. options.callback(el)
  176. }
  177. } catch (e) {
  178. if (options.stopOnError) {
  179. throw e
  180. } else {
  181. options.onError?.(e)
  182. }
  183. }
  184. return success
  185. }
  186. const task = root => {
  187. let success = false
  188. if (options.multiple) {
  189. root.querySelectorAll(options.selector).forEach(el => {
  190. success = singleTask(el)
  191. })
  192. } else if (options.repeat) {
  193. const elements = root.querySelectorAll(options.selector)
  194. for (let i = elements.length - 1; i >= 0; i--) {
  195. const el = elements[i]
  196. if (success) {
  197. if (valid(el)) {
  198. excluded.add(el)
  199. }
  200. } else {
  201. success = singleTask(el)
  202. }
  203. }
  204. } else {
  205. const el = root.querySelector(options.selector)
  206. success = el && singleTask(el)
  207. }
  208. loaded ||= success
  209. if (loaded && !options.repeat) {
  210. stop()
  211. }
  212. return success
  213. }
  214. const throttledTask = options.throttleWait > 0 ? api.tool.throttle(task, options.throttleWait) : task
  215.  
  216. const ob = new MutationObserver(() => {
  217. if (stopped) return
  218. try {
  219. if (options.stopCondition?.()) {
  220. stop()
  221. options.onStop?.()
  222. return
  223. }
  224. throttledTask(options.base)
  225. } catch (e) {
  226. options.onError?.(e)
  227. if (options.stopOnError) {
  228. stop()
  229. }
  230. }
  231. })
  232.  
  233. setTimeout(() => {
  234. if (stopped) return
  235. try {
  236. if (options.stopCondition?.()) {
  237. stop()
  238. options.onStop?.()
  239. return
  240. }
  241. task(options.base)
  242. } catch (e) {
  243. options.onError?.(e)
  244. if (options.stopOnError) {
  245. stop()
  246. }
  247. }
  248. if (stopped) return
  249. ob.observe(options.base, {
  250. childList: true,
  251. subtree: options.subtree,
  252. })
  253. if (options.timeout > 0) {
  254. tid = setTimeout(() => {
  255. if (stopped) return
  256. tid = null
  257. if (!loaded) {
  258. if (options.stopOnTimeout) {
  259. stop()
  260. }
  261. options.onTimeout?.()
  262. } else { // 只要检测到,无论重复与否,都不算超时;需永久检测必须设 timeout 为 0
  263. stop()
  264. }
  265. }, Math.max(options.timeout - options.timePadding, 0))
  266. }
  267. }, options.timePadding)
  268. return stop
  269. }
  270.  
  271. /**
  272. * 等待条件达成
  273. *
  274. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  275. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  276. * @param {() => (* | Promise)} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  277. * @param {number} [options.interval] 检测时间间隔
  278. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  279. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  280. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  281. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  282. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  283. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  284. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  285. * @returns {Promise} `result`
  286. * @throws 等待超时、达成终止条件、等待错误时抛出
  287. * @see executeAfterConditionPassed
  288. */
  289. async waitForConditionPassed(options) {
  290. const api = this.api
  291. return new Promise((resolve, reject) => {
  292. this.executeAfterConditionPassed({
  293. ...options,
  294. callback: result => resolve(result),
  295. onTimeout: function() {
  296. const error = ['TIMEOUT', 'waitForConditionPassed', this]
  297. if (this.stopOnTimeout) {
  298. reject(error)
  299. } else {
  300. api.logger.warn(error)
  301. }
  302. },
  303. onStop: function() {
  304. reject(['STOP', 'waitForConditionPassed', this])
  305. },
  306. onError: function(e) {
  307. reject(['ERROR', 'waitForConditionPassed', this, e])
  308. },
  309. })
  310. })
  311. }
  312.  
  313. /**
  314. * 等待元素加载完成
  315. *
  316. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  317. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  318. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  319. * @param {HTMLElement} [options.base] 基元素
  320. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  321. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  322. * @param {number} [options.throttleWait] 检测节流时间(非准确)
  323. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  324. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  325. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  326. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  327. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  328. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  329. * @returns {Promise<HTMLElement>} `element`
  330. * @throws 等待超时、达成终止条件、等待错误时抛出
  331. * @see executeAfterElementLoaded
  332. */
  333. async waitForElementLoaded(options) {
  334. const api = this.api
  335. return new Promise((resolve, reject) => {
  336. this.executeAfterElementLoaded({
  337. ...options,
  338. callback: element => resolve(element),
  339. onTimeout: function() {
  340. const error = ['TIMEOUT', 'waitForElementLoaded', this]
  341. if (this.stopOnTimeout) {
  342. reject(error)
  343. } else {
  344. api.logger.warn(error)
  345. }
  346. },
  347. onStop: function() {
  348. reject(['STOP', 'waitForElementLoaded', this])
  349. },
  350. onError: function(e) {
  351. reject(['ERROR', 'waitForElementLoaded', this, e])
  352. },
  353. })
  354. })
  355. }
  356.  
  357. /**
  358. * 元素加载选择器
  359. *
  360. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  361. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  362. * @param {HTMLElement} [base=UserscriptAPI.options.wait.element.base] 基元素
  363. * @param {boolean} [stopOnTimeout=UserscriptAPI.options.wait.element.stopOnTimeout] 检测超时时是否终止检测
  364. * @returns {Promise<HTMLElement>} `element`
  365. * @throws 等待超时、达成终止条件、等待错误时抛出
  366. * @see executeAfterElementLoaded
  367. */
  368. async $(selector, base = this.api.options.wait.element.base, stopOnTimeout = this.api.options.wait.element.stopOnTimeout) {
  369. const api = this.api
  370. return new Promise((resolve, reject) => {
  371. this.executeAfterElementLoaded({
  372. ...{ selector, base, stopOnTimeout },
  373. callback: element => resolve(element),
  374. onTimeout: function() {
  375. const error = ['TIMEOUT', 'waitQuerySelector', this]
  376. if (this.stopOnTimeout) {
  377. reject(error)
  378. } else {
  379. api.logger.warn(error)
  380. }
  381. },
  382. onStop: function() {
  383. reject(['STOP', 'waitQuerySelector', this])
  384. },
  385. onError: function(e) {
  386. reject(['ERROR', 'waitQuerySelector', this, e])
  387. },
  388. })
  389. })
  390. }
  391. }
  392.  
  393. /* global UserscriptAPI */
  394. { UserscriptAPI.registerModule('wait', UserscriptAPIWait) }