UserscriptAPI

My API for userscripts.

Verze ze dne 17. 07. 2021. Zobrazit nejnovější verzi.

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greatest.deepsurf.us/scripts/409641/951336/UserscriptAPI.js

  1. /* exported UserscriptAPI */
  2. /**
  3. * UserscriptAPI
  4. *
  5. * 根据使用到的功能,可能需要通过 `@grant` 引入 `GM_xmlhttpRequest` 或 `GM_download`。
  6. *
  7. * 如无特殊说明,涉及到时间时所用单位均为毫秒。
  8. * @version 1.2.4.20210717
  9. * @author Laster2800
  10. */
  11. class UserscriptAPI {
  12. /**
  13. * @param {Object} [options] 选项
  14. * @param {string} [options.id='_0'] 标识符
  15. * @param {string} [options.label] 日志标签,为空时不设置标签
  16. * @param {Object} [options.wait] `wait` API 默认选项(默认值见构造器代码)
  17. * @param {Object} [options.wait.condition] `wait` 条件 API 默认选项
  18. * @param {Object} [options.wait.element] `wait` 元素 API 默认选项
  19. * @param {number} [options.fadeTime=400] UI 渐变时间
  20. */
  21. constructor(options) {
  22. this.options = {
  23. id: '_0',
  24. label: null,
  25. fadeTime: 400,
  26. ...options,
  27. wait: {
  28. condition: {
  29. callback: result => api.logger.info(result),
  30. interval: 100,
  31. timeout: 10000,
  32. onTimeout: function() {
  33. api.logger[this.stopOnTimeout ? 'error' : 'warn'](['TIMEOUT', 'executeAfterConditionPassed', options])
  34. },
  35. stopOnTimeout: true,
  36. stopCondition: null,
  37. onStop: () => api.logger.error(['STOP', 'executeAfterConditionPassed', options]),
  38. stopInterval: 50,
  39. stopTimeout: 0,
  40. onError: () => api.logger.error(['ERROR', 'executeAfterConditionPassed', options]),
  41. stopOnError: true,
  42. timePadding: 0,
  43. ...options?.wait?.condition,
  44. },
  45. element: {
  46. base: document,
  47. exclude: null,
  48. callback: el => api.logger.info(el),
  49. subtree: true,
  50. multiple: false,
  51. repeat: false,
  52. throttleWait: 100,
  53. timeout: 10000,
  54. onTimeout: function() {
  55. api.logger[this.stopOnTimeout ? 'error' : 'warn'](['TIMEOUT', 'executeAfterElementLoaded', options])
  56. },
  57. stopOnTimeout: false,
  58. stopCondition: null,
  59. onStop: () => api.logger.error(['STOP', 'executeAfterElementLoaded', options]),
  60. onError: () => api.logger.error(['ERROR', 'executeAfterElementLoaded', options]),
  61. stopOnError: true,
  62. timePadding: 0,
  63. ...options?.wait?.element,
  64. },
  65. },
  66. }
  67.  
  68. const original = window[`_api_${this.options.id}`]
  69. if (original) {
  70. original.options = this.options
  71. return original
  72. }
  73. window[`_api_${this.options.id}`] = this
  74.  
  75. const api = this
  76. const logCss = `
  77. background-color: black;
  78. color: white;
  79. border-radius: 2px;
  80. padding: 2px;
  81. margin-right: 2px;
  82. `
  83.  
  84. /** DOM 相关 */
  85. this.dom = {
  86. /**
  87. * 初始化 urlchange 事件
  88. * @see {@link https://stackoverflow.com/a/52809105 How to detect if URL has changed after hash in JavaScript}
  89. */
  90. initUrlchangeEvent() {
  91. if (!history._urlchangeEventInitialized) {
  92. const urlEvent = () => {
  93. const event = new Event('urlchange')
  94. // 添加属性,使其与 Tampermonkey urlchange 保持一致
  95. event.url = location.href
  96. return event
  97. }
  98. history.pushState = (f => function pushState() {
  99. const ret = f.apply(this, arguments)
  100. window.dispatchEvent(new Event('pushstate'))
  101. window.dispatchEvent(urlEvent())
  102. return ret
  103. })(history.pushState)
  104. history.replaceState = (f => function replaceState() {
  105. const ret = f.apply(this, arguments)
  106. window.dispatchEvent(new Event('replacestate'))
  107. window.dispatchEvent(urlEvent())
  108. return ret
  109. })(history.replaceState)
  110. window.addEventListener('popstate', () => {
  111. window.dispatchEvent(urlEvent())
  112. })
  113. history._urlchangeEventInitialized = true
  114. }
  115. },
  116.  
  117. /**
  118. * 将一个元素绝对居中
  119. *
  120. * 要求该元素此时可见且尺寸为确定值(一般要求为块状元素)。运行后会在 `target` 上附加 `_absoluteCenter` 方法,若该方法已存在,则无视 `config` 直接执行 `target._absoluteCenter()`。
  121. * @param {HTMLElement} target 目标元素
  122. * @param {Object} [config] 配置
  123. * @param {string} [config.position='fixed'] 定位方式
  124. * @param {string} [config.top='50%'] `style.top`
  125. * @param {string} [config.left='50%'] `style.left`
  126. */
  127. setAbsoluteCenter(target, config) {
  128. if (!target._absoluteCenter) {
  129. const defaultConfig = {
  130. position: 'fixed',
  131. top: '50%',
  132. left: '50%',
  133. }
  134. config = { ...defaultConfig, ...config }
  135. target._absoluteCenter = () => {
  136. target.style.position = config.position
  137. const style = getComputedStyle(target)
  138. const top = (parseFloat(style.height) + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)) / 2
  139. const left = (parseFloat(style.width) + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight)) / 2
  140. target.style.top = `calc(${config.top} - ${top}px)`
  141. target.style.left = `calc(${config.left} - ${left}px)`
  142. }
  143. window.addEventListener('resize', api.tool.throttle(target._absoluteCenter), 100)
  144. }
  145. target._absoluteCenter()
  146. },
  147.  
  148. /**
  149. * 处理 HTML 元素的渐显和渐隐
  150. * @param {boolean} inOut 渐显/渐隐
  151. * @param {HTMLElement} target HTML 元素
  152. * @param {() => void} [callback] 处理完成的回调函数
  153. */
  154. fade(inOut, target, callback) {
  155. // fadeId 等同于当前时间戳,其意义在于保证对于同一元素,后执行的操作必将覆盖前的操作
  156. const fadeId = new Date().getTime()
  157. target._fadeId = fadeId
  158. if (inOut) { // 渐显
  159. // 只有 display 可视情况下修改 opacity 才会触发 transition
  160. if (getComputedStyle(target).display == 'none') {
  161. target.style.display = 'unset'
  162. }
  163. setTimeout(() => {
  164. let success = false
  165. if (target._fadeId <= fadeId) {
  166. target.style.opacity = '1'
  167. success = true
  168. }
  169. callback?.(success)
  170. }, 10) // 此处的 10ms 是为了保证修改 display 后在浏览器上真正生效,按 HTML5 定义,浏览器需保证 display 在修改 4ms 后保证生效,但实际上大部分浏览器貌似做不到,等个 10ms 再修改 opacity
  171. } else { // 渐隐
  172. target.style.opacity = '0'
  173. setTimeout(() => {
  174. let success = false
  175. if (target._fadeId <= fadeId) {
  176. target.style.display = 'none'
  177. success = true
  178. }
  179. callback?.(success)
  180. }, api.options.fadeTime)
  181. }
  182. },
  183.  
  184. /**
  185. * 为 HTML 元素添加 `class`
  186. * @param {HTMLElement} el 目标元素
  187. * @param {...string} className `class`
  188. */
  189. addClass(el, ...className) {
  190. el.classList?.add(...className)
  191. },
  192.  
  193. /**
  194. * 为 HTML 元素移除 `class`
  195. * @param {HTMLElement} el 目标元素
  196. * @param {...string} [className] `class`,未指定时移除所有 `class`
  197. */
  198. removeClass(el, ...className) {
  199. if (className.length > 0) {
  200. el.classList?.remove(...className)
  201. } else if (el.className) {
  202. el.className = ''
  203. }
  204. },
  205.  
  206. /**
  207. * 判断 HTML 元素类名中是否含有 `class`
  208. * @param {HTMLElement | {className: string}} el 目标元素
  209. * @param {string | string[]} className `class`,支持同时判断多个
  210. * @param {boolean} [and] 同时判断多个 `class` 时,默认采取 `OR` 逻辑,是否采用 `AND` 逻辑
  211. * @returns {boolean} 是否含有 `class`
  212. */
  213. containsClass(el, className, and = false) {
  214. const trim = clz => clz.startsWith('.') ? clz.slice(1) : clz
  215. if (el.classList) {
  216. if (className instanceof Array) {
  217. if (and) {
  218. for (const c of className) {
  219. if (!el.classList.contains(trim(c))) {
  220. return false
  221. }
  222. }
  223. return true
  224. } else {
  225. for (const c of className) {
  226. if (el.classList.contains(trim(c))) {
  227. return true
  228. }
  229. }
  230. return false
  231. }
  232. } else {
  233. return el.classList.contains(trim(className))
  234. }
  235. }
  236. return false
  237. },
  238.  
  239. /**
  240. * 判断 HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  241. * @param {HTMLElement} el 目标元素
  242. * @param {HTMLElement} [endEl] 终止元素,当搜索到该元素时终止判断(不会判断该元素)
  243. * @returns {boolean} HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  244. */
  245. isFixed(el, endEl) {
  246. while (el instanceof HTMLElement && el != endEl) {
  247. if (window.getComputedStyle(el).position == 'fixed') {
  248. return true
  249. }
  250. el = el.parentNode
  251. }
  252. return false
  253. },
  254. }
  255. /** 信息通知相关 */
  256. this.message = {
  257. /**
  258. * 创建信息
  259. * @param {string} msg 信息
  260. * @param {Object} [config] 设置
  261. * @param {boolean} [config.autoClose=true] 是否自动关闭信息,配合 `config.ms` 使用
  262. * @param {number} [config.ms=1500] 显示时间(单位:ms,不含渐显/渐隐时间)
  263. * @param {boolean} [config.html=false] 是否将 `msg` 理解为 HTML
  264. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  265. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,相当于设置为 `{ top: '70%', left: '50%' }`
  266. * @return {HTMLElement} 信息框元素
  267. */
  268. create(msg, config) {
  269. const defaultConfig = {
  270. autoClose: true,
  271. ms: 1500,
  272. html: false,
  273. width: null,
  274. position: {
  275. top: '70%',
  276. left: '50%',
  277. },
  278. }
  279. config = { ...defaultConfig, ...config }
  280.  
  281. const msgbox = document.createElement('div')
  282. msgbox.className = `${api.options.id}-msgbox`
  283. if (config.width) {
  284. msgbox.style.minWidth = 'auto' // 为什么一个是 auto 一个是 none?真是神奇的设计
  285. msgbox.style.maxWidth = 'none'
  286. msgbox.style.width = config.width
  287. }
  288. msgbox.style.display = 'block'
  289. if (config.html) {
  290. msgbox.innerHTML = msg
  291. } else {
  292. msgbox.innerText = msg
  293. }
  294. document.body.appendChild(msgbox)
  295. setTimeout(() => {
  296. api.dom.setAbsoluteCenter(msgbox, config.position)
  297. }, 10)
  298.  
  299. api.dom.fade(true, msgbox, () => {
  300. if (config.autoClose) {
  301. setTimeout(() => {
  302. this.close(msgbox)
  303. }, config.ms)
  304. }
  305. })
  306. return msgbox
  307. },
  308.  
  309. /**
  310. * 关闭信息
  311. * @param {HTMLElement} msgbox 信息框元素
  312. */
  313. close(msgbox) {
  314. if (msgbox) {
  315. api.dom.fade(false, msgbox, () => {
  316. msgbox?.remove()
  317. })
  318. }
  319. },
  320.  
  321. /**
  322. * 创建高级信息
  323. * @param {HTMLElement} el 启动元素
  324. * @param {string} msg 信息
  325. * @param {string} flag 标志信息
  326. * @param {Object} [config] 设置
  327. * @param {string} [config.flagSize='1.8em'] 标志大小
  328. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  329. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,沿用 `UserscriptAPI.message.create()` 的默认设置
  330. * @param {() => boolean} [config.disabled] 用于获取是否禁用信息的方法
  331. */
  332. advanced(el, msg, flag, config) {
  333. const defaultConfig = {
  334. flagSize: '1.8em',
  335. // 不能把数据列出,否则解构的时候会出问题
  336. }
  337. config = { ...defaultConfig, ...config }
  338.  
  339. const _self = this
  340. el.show = false
  341. el.onmouseenter = function() {
  342. if (config.disabled?.()) return
  343. const htmlMsg = `
  344. <table class="gm-advanced-table"><tr>
  345. <td style="font-size:${config.flagSize};line-height:${config.flagSize}">${flag}</td>
  346. <td>${msg}</td>
  347. </tr></table>
  348. `
  349. this.msgbox = _self.create(htmlMsg, { ...config, html: true, autoClose: false })
  350.  
  351. // 可能信息框刚好生成覆盖在 el 上,需要做一个处理
  352. this.msgbox.onmouseenter = function() {
  353. this.mouseOver = true
  354. }
  355. // 从信息框出来也会关闭信息框,防止覆盖的情况下无法关闭
  356. this.msgbox.onmouseleave = function() {
  357. _self.close(this)
  358. }
  359. }
  360. el.onmouseleave = function() {
  361. setTimeout(() => {
  362. if (this.msgbox && !this.msgbox.mouseOver) {
  363. this.msgbox.onmouseleave = null
  364. _self.close(this.msgbox)
  365. }
  366. })
  367. }
  368. },
  369. }
  370. /** 用于等待元素加载/条件达成再执行操作 */
  371. this.wait = {
  372. /**
  373. * 在条件达成后执行操作
  374. *
  375. * 当条件达成后,如果不存在终止条件,那么直接执行 `callback(result)`。
  376. *
  377. * 当条件达成后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否达成终止条件,称为终止条件的二次判断。如果在此期间,终止条件通过,则表示依然不达成条件,故执行 `onStop()` 而非 `callback(result)`。如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  378. *
  379. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  380. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  381. * @param {(result) => void} [options.callback] 当达成条件时执行 `callback(result)`
  382. * @param {number} [options.interval] 检测时间间隔
  383. * @param {number} [options.timeout] 检测超时时间(非准确),检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  384. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  385. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  386. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  387. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  388. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  389. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间(非准确),设置为 `0` 时禁用终止条件二次判断
  390. * @param {(e) => void} [options.onError] 条件检测过程中发生错误时执行 `onError()`
  391. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  392. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  393. * @returns {() => boolean} 执行后终止检测的函数
  394. */
  395. executeAfterConditionPassed(options) {
  396. options = {
  397. ...api.options.wait.condition,
  398. ...options,
  399. }
  400. let stop = false
  401. let cnt = 0
  402. let maxCnt = null
  403. if (options.timeout === 0) {
  404. maxCnt = 0
  405. } else {
  406. maxCnt = (options.timeout - options.timePadding) / options.interval
  407. }
  408. const task = async () => {
  409. if (stop) return
  410. let result = null
  411. try {
  412. result = await options.condition()
  413. } catch (e) {
  414. options.onError?.call(options, e)
  415. if (options.stopOnError) {
  416. stop = true
  417. }
  418. }
  419. if (stop) return
  420. const stopResult = await options.stopCondition?.()
  421. if (stopResult) {
  422. stop = true
  423. options.onStop?.call(options)
  424. } else if (maxCnt !== 0 && ++cnt > maxCnt) {
  425. if (options.stopOnTimeout) {
  426. stop = true
  427. } else {
  428. maxCnt = 0
  429. }
  430. options.onTimeout?.call(options)
  431. } else if (result) {
  432. stop = true
  433. if (options.stopCondition && options.stopTimeout > 0) {
  434. this.executeAfterConditionPassed({
  435. condition: options.stopCondition,
  436. callback: options.onStop,
  437. interval: options.stopInterval,
  438. timeout: options.stopTimeout,
  439. onTimeout: () => options.callback.call(options, result)
  440. })
  441. } else {
  442. options.callback.call(options, result)
  443. }
  444. }
  445. if (!stop) {
  446. setTimeout(task, options.interval)
  447. }
  448. }
  449. setTimeout(async () => {
  450. if (stop) return
  451. await task()
  452. if (stop) return
  453. setTimeout(task, options.interval)
  454. }, options.timePadding)
  455. return function() {
  456. stop = true
  457. }
  458. },
  459.  
  460. /**
  461. * 在元素加载完成后执行操作
  462. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  463. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  464. * @param {HTMLElement} [options.base] 基元素
  465. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  466. * @param {(element: HTMLElement) => void} [options.callback] 当 `element` 加载成功时执行 `callback(element)`
  467. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  468. * @param {boolean} [options.multiple] 若一次检测到多个目标元素,是否在所有元素上执行回调函数(否则只处理第一个结果)
  469. * @param {boolean} [options.repeat] `element` 加载成功后是否继续检测
  470. * @param {number} [options.throttleWait] 检测节流时间(非准确);节流控制仅当 `repeat` 为 `false` 时生效,设置为 `0` 时禁用节流控制
  471. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  472. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  473. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  474. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  475. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  476. * @param {(e) => void} [options.onError] 检测过程中发生错误时执行 `onError()`
  477. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  478. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  479. * @returns {() => boolean} 执行后终止检测的函数
  480. */
  481. executeAfterElementLoaded(options) {
  482. options = {
  483. ...api.options.wait.element,
  484. ...options,
  485. }
  486.  
  487. let loaded = false
  488. let stopped = false
  489.  
  490. const stop = () => {
  491. if (!stopped) {
  492. stopped = true
  493. ob.disconnect()
  494. }
  495. }
  496.  
  497. const isExcluded = element => {
  498. return options.exclude?.indexOf(element) >= 0
  499. }
  500.  
  501. const task = root => {
  502. let success = false
  503. if (options.multiple) {
  504. const elements = root.querySelectorAll(options.selector)
  505. if (elements.length > 0) {
  506. for (const element of elements) {
  507. if (!isExcluded(element)) {
  508. success = true
  509. options.callback.call(options, element)
  510. }
  511. }
  512. }
  513. } else {
  514. const element = root.querySelector(options.selector)
  515. if (element && !isExcluded(element)) {
  516. success = true
  517. options.callback.call(options, element)
  518. }
  519. }
  520. loaded = success || loaded
  521. return success
  522. }
  523. const singleTask = (!options.repeat && options.throttleWait > 0) ? api.tool.throttle(task, options.throttleWait) : task
  524.  
  525. const repeatTask = records => {
  526. let success = false
  527. for (const record of records) {
  528. for (const addedNode of record.addedNodes) {
  529. if (addedNode instanceof HTMLElement) {
  530. const virtualRoot = document.createElement('div')
  531. virtualRoot.appendChild(addedNode.cloneNode())
  532. const el = virtualRoot.querySelector(options.selector)
  533. if (el && !isExcluded(addedNode)) {
  534. success = true
  535. loaded = true
  536. options.callback.call(options, addedNode)
  537. if (!options.multiple) {
  538. return true
  539. }
  540. }
  541. success = task(addedNode) || success
  542. if (success && !options.multiple) {
  543. return true
  544. }
  545. }
  546. }
  547. }
  548. }
  549.  
  550. const ob = new MutationObserver(records => {
  551. try {
  552. if (stopped) {
  553. return
  554. } else if (options.stopCondition?.()) {
  555. stop()
  556. options.onStop?.call(options)
  557. return
  558. }
  559. if (options.repeat) {
  560. repeatTask(records)
  561. } else {
  562. singleTask(options.base)
  563. }
  564. if (loaded && !options.repeat) {
  565. stop()
  566. }
  567. } catch (e) {
  568. options.onError?.call(options, e)
  569. if (options.stopOnError) {
  570. stop()
  571. }
  572. }
  573. })
  574.  
  575. setTimeout(() => {
  576. try {
  577. if (!stopped) {
  578. if (options.stopCondition?.()) {
  579. stop()
  580. options.onStop?.call(options)
  581. return
  582. }
  583. task(options.base)
  584. }
  585. } catch (e) {
  586. options.onError?.call(options, e)
  587. if (options.stopOnError) {
  588. stop()
  589. }
  590. }
  591. if (!stopped) {
  592. if (!loaded || options.repeat) {
  593. ob.observe(options.base, {
  594. childList: true,
  595. subtree: options.subtree,
  596. })
  597. if (options.timeout > 0) {
  598. setTimeout(() => {
  599. if (!stopped) {
  600. if (!loaded) {
  601. if (options.stopOnTimeout) {
  602. stop()
  603. }
  604. options.onTimeout?.call(options)
  605. } else { // 只要检测到,无论重复与否,都不算超时;需永久检测必须设 timeout 为 0
  606. stop()
  607. }
  608. }
  609. }, Math.max(options.timeout - options.timePadding, 0))
  610. }
  611. }
  612. }
  613. }, options.timePadding)
  614. return stop
  615. },
  616.  
  617. /**
  618. * 等待条件达成
  619. *
  620. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  621. * @async
  622. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  623. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  624. * @param {number} [options.interval] 检测时间间隔
  625. * @param {number} [options.timeout] 检测超时时间(非准确),检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  626. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  627. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  628. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  629. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间(非准确),设置为 `0` 时禁用终止条件二次判断
  630. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  631. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  632. * @returns {Promise} `result`
  633. * @throws 等待超时、达成终止条件、等待错误时抛出
  634. * @see executeAfterConditionPassed
  635. */
  636. async waitForConditionPassed(options) {
  637. return new Promise((resolve, reject) => {
  638. this.executeAfterConditionPassed({
  639. ...options,
  640. callback: result => resolve(result),
  641. onTimeout: function() {
  642. const error = ['TIMEOUT', 'waitForConditionPassed', this]
  643. if (this.stopOnTimeout) {
  644. reject(error)
  645. } else {
  646. api.logger.warn(error)
  647. }
  648. },
  649. onStop: function() {
  650. reject(['STOP', 'waitForConditionPassed', this])
  651. },
  652. onError: function(e) {
  653. reject(['ERROR', 'waitForConditionPassed', this, e])
  654. },
  655. })
  656. })
  657. },
  658.  
  659. /**
  660. * 等待元素加载完成
  661. *
  662. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  663. * @async
  664. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  665. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  666. * @param {HTMLElement} [options.base] 基元素
  667. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  668. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  669. * @param {number} [options.throttleWait] 检测节流时间(非准确);节流控制仅当 `repeat` 为 `false` 时生效,设置为 `0` 时禁用节流控制
  670. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  671. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  672. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  673. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  674. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  675. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  676. * @returns {Promise<HTMLElement>} `element`
  677. * @throws 等待超时、达成终止条件、等待错误时抛出
  678. * @see executeAfterElementLoaded
  679. */
  680. async waitForElementLoaded(options) {
  681. return new Promise((resolve, reject) => {
  682. this.executeAfterElementLoaded({
  683. ...options,
  684. callback: element => resolve(element),
  685. onTimeout: function() {
  686. const error = ['TIMEOUT', 'waitForElementLoaded', this]
  687. if (this.stopOnTimeout) {
  688. reject(error)
  689. } else {
  690. api.logger.warn(error)
  691. }
  692. },
  693. onStop: function() {
  694. reject(['STOP', 'waitForElementLoaded', this])
  695. },
  696. onError: function() {
  697. reject(['ERROR', 'waitForElementLoaded', this])
  698. },
  699. })
  700. })
  701. },
  702.  
  703. /**
  704. * 元素加载选择器
  705. *
  706. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  707. * @async
  708. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  709. * @param {HTMLElement} [base=UserscriptAPI.options.wait.element.base] 基元素
  710. * @param {boolean} [stopOnTimeout=UserscriptAPI.options.wait.element.stopOnTimeout] 检测超时时是否终止检测
  711. * @returns {Promise<HTMLElement>} `element`
  712. * @throws 等待超时、达成终止条件、等待错误时抛出
  713. * @see executeAfterElementLoaded
  714. */
  715. async waitQuerySelector(selector, base = api.options.wait.element.base, stopOnTimeout = api.options.wait.element.stopOnTimeout) {
  716. return new Promise((resolve, reject) => {
  717. this.executeAfterElementLoaded({
  718. ... { selector, base, stopOnTimeout },
  719. callback: element => resolve(element),
  720. onTimeout: function() {
  721. const error = ['TIMEOUT', 'waitQuerySelector', this]
  722. if (this.stopOnTimeout) {
  723. reject(error)
  724. } else {
  725. api.logger.warn(error)
  726. }
  727. },
  728. onStop: function() {
  729. reject(['STOP', 'waitQuerySelector', this])
  730. },
  731. onError: function() {
  732. reject(['ERROR', 'waitQuerySelector', this])
  733. },
  734. })
  735. })
  736. },
  737. }
  738. /** 网络相关 */
  739. this.web = {
  740. /** @typedef {Object} GM_xmlhttpRequest_details */
  741. /** @typedef {Object} GM_xmlhttpRequest_response */
  742. /**
  743. * 发起网络请求
  744. * @async
  745. * @param {GM_xmlhttpRequest_details} details 定义及细节同 {@link GM_xmlhttpRequest} 的 `details`
  746. * @returns {Promise<GM_xmlhttpRequest_response>} 响应对象
  747. * @throws 等待超时、达成终止条件、等待错误时抛出
  748. * @see {@link https://www.tampermonkey.net/documentation.php#GM_xmlhttpRequest GM_xmlhttpRequest}
  749. */
  750. async request(details) {
  751. if (details) {
  752. return new Promise((resolve, reject) => {
  753. const throwHandler = function(msg) {
  754. api.logger.error('NETWORK REQUEST ERROR')
  755. reject(msg)
  756. }
  757. details.onerror = details.onerror ?? (() => throwHandler(['ERROR', 'request', details]))
  758. details.ontimeout = details.ontimeout ?? (() => throwHandler(['TIMEOUT', 'request', details]))
  759. details.onload = details.onload ?? (response => resolve(response))
  760. GM_xmlhttpRequest(details)
  761. })
  762. }
  763. },
  764.  
  765. /** @typedef {Object} GM_download_details */
  766. /**
  767. * 下载资源
  768. * @param {GM_download_details} details 定义及细节同 {@link GM_download} 的 `details`
  769. * @returns {() => void} 用于终止下载的方法
  770. * @see {@link https://www.tampermonkey.net/documentation.php#GM_download GM_download}
  771. */
  772. download(details) {
  773. if (details) {
  774. try {
  775. const cfg = { ...details }
  776. let name = cfg.name
  777. if (name.indexOf('.') > -1) {
  778. let parts = cfg.url.split('/')
  779. const last = parts[parts.length - 1].split('?')[0]
  780. if (last.indexOf('.') > -1) {
  781. parts = last.split('.')
  782. name = `${name}.${parts[parts.length - 1]}`
  783. } else {
  784. name = name.replaceAll('.', '_')
  785. }
  786. cfg.name = name
  787. }
  788. if (!cfg.onerror) {
  789. cfg.onerror = function(error, details) {
  790. api.logger.error('DOWNLOAD ERROR')
  791. api.logger.error([error, details])
  792. }
  793. }
  794. if (!cfg.ontimeout) {
  795. cfg.ontimeout = function() {
  796. api.logger.error('DOWNLOAD TIMEOUT')
  797. }
  798. }
  799. GM_download(cfg)
  800. } catch (e) {
  801. api.logger.error('DOWNLOAD ERROR')
  802. api.logger.error(e)
  803. }
  804. }
  805. return () => {}
  806. },
  807.  
  808. /**
  809. * 判断给定 URL 是否匹配
  810. * @param {RegExp | RegExp[]} reg 用于判断是否匹配的正则表达式,或正则表达式数组
  811. * @param {'SINGLE' | 'AND' | 'OR'} [mode='SINGLE'] 匹配模式
  812. * @returns {boolean} 是否匹配
  813. */
  814. urlMatch(reg, mode = 'SINGLE') {
  815. let result = false
  816. const href = location.href
  817. if (mode == 'SINGLE') {
  818. if (reg instanceof Array) {
  819. if (reg.length > 0) {
  820. reg = reg[0]
  821. } else {
  822. reg = null
  823. }
  824. }
  825. if (reg) {
  826. result = reg.test(href)
  827. }
  828. } else {
  829. if (!(reg instanceof Array)) {
  830. reg = [reg]
  831. }
  832. if (reg.length > 0) {
  833. if (mode == 'AND') {
  834. result = true
  835. for (const r of reg) {
  836. if (!r.test(href)) {
  837. result = false
  838. break
  839. }
  840. }
  841. } else if (mode == 'OR') {
  842. for (const r of reg) {
  843. if (r.test(href)) {
  844. result = true
  845. break
  846. }
  847. }
  848. }
  849. }
  850. }
  851. return result
  852. },
  853. }
  854. /**
  855. * 日志
  856. */
  857. this.logger = {
  858. /**
  859. * 打印格式化日志
  860. * @param {*} message 日志信息
  861. * @param {string} label 日志标签
  862. * @param {'info', 'warn', 'error'} [level] 日志等级
  863. */
  864. log(message, label, level = 'info') {
  865. const output = console[level == 'info' ? 'log' : level]
  866. const type = typeof message == 'string' ? '%s' : '%o'
  867. output(`%c${label}%c${type}`, logCss, '', message)
  868. },
  869.  
  870. /**
  871. * 打印日志
  872. * @param {*} message 日志信息
  873. */
  874. info(message) {
  875. if (message === undefined) {
  876. message = '[undefined]'
  877. } else if (message === null) {
  878. message = '[null]'
  879. } else if (message === '') {
  880. message = '[empty string]'
  881. }
  882. if (api.options.label) {
  883. this.log(message, api.options.label)
  884. } else {
  885. console.log(message)
  886. }
  887. },
  888.  
  889. /**
  890. * 打印警告日志
  891. * @param {*} message 警告日志信息
  892. */
  893. warn(message) {
  894. if (message === undefined) {
  895. message = '[undefined]'
  896. } else if (message === null) {
  897. message = '[null]'
  898. } else if (message === '') {
  899. message = '[empty string]'
  900. }
  901. if (api.options.label) {
  902. this.log(message, api.options.label, 'warn')
  903. } else {
  904. console.warn(message)
  905. }
  906. },
  907.  
  908. /**
  909. * 打印错误日志
  910. * @param {*} message 错误日志信息
  911. */
  912. error(message) {
  913. if (message === undefined) {
  914. message = '[undefined]'
  915. } else if (message === null) {
  916. message = '[null]'
  917. } else if (message === '') {
  918. message = '[empty string]'
  919. }
  920. if (api.options.label) {
  921. this.log(message, api.options.label, 'error')
  922. } else {
  923. console.error(message)
  924. }
  925. },
  926. }
  927. /**
  928. * 工具
  929. */
  930. this.tool = {
  931. /**
  932. * 生成消抖函数
  933. * @param {Function} fn 目标函数
  934. * @param {number} [wait=0] 消抖延迟
  935. * @param {Object} [options] 选项
  936. * @param {boolean} [options.leading] 是否在延迟开始前调用目标函数
  937. * @param {boolean} [options.trailing=true] 是否在延迟结束后调用目标函数
  938. * @param {number} [options.maxWait=0] 最大延迟时间(非准确),`0` 表示禁用
  939. * @returns {Function} 消抖函数 `debounced`,可调用 `debounced.cancel()` 取消执行
  940. */
  941. debounce(fn, wait = 0, options = {}) {
  942. options = {
  943. leading: false,
  944. trailing: true,
  945. maxWait: 0,
  946. ...options,
  947. }
  948.  
  949. let tid = null
  950. let start = null
  951. let execute = null
  952. let callback = null
  953.  
  954. function debounced() {
  955. execute = () => {
  956. fn.apply(null, arguments)
  957. execute = null
  958. }
  959. callback = () => {
  960. if (options.trailing) {
  961. execute?.()
  962. }
  963. tid = null
  964. start = null
  965. }
  966.  
  967. if (tid) {
  968. clearTimeout(tid)
  969. if (options.maxWait > 0 && new Date().getTime() - start > options.maxWait) {
  970. callback()
  971. }
  972. }
  973.  
  974. if (!tid && options.leading) {
  975. execute?.()
  976. }
  977.  
  978. if (!start) {
  979. start = new Date().getTime()
  980. }
  981.  
  982. tid = setTimeout(callback, wait)
  983. }
  984.  
  985. debounced.cancel = function() {
  986. if (tid) {
  987. clearTimeout(tid)
  988. tid = null
  989. start = null
  990. }
  991. }
  992.  
  993. return debounced
  994. },
  995.  
  996. /**
  997. * 生成节流函数
  998. * @param {Function} fn 目标函数
  999. * @param {number} [wait=0] 节流延迟(非准确)
  1000. * @returns {Function} 节流函数 `throttled`,可调用 `throttled.cancel()` 取消执行
  1001. */
  1002. throttle(fn, wait = 0) {
  1003. return this.debounce(fn, wait, {
  1004. leading: true,
  1005. trailing: true,
  1006. maxWait: wait,
  1007. })
  1008. },
  1009. }
  1010.  
  1011. const css = document.head.appendChild(document.createElement('style'))
  1012. css.id = `_api_${api.options.id}-css`
  1013. css.type = 'text/css'
  1014. css.innerHTML = `
  1015. :root {
  1016. --light-text-color: white;
  1017. --shadow-color: #000000bf;
  1018. }
  1019.  
  1020. .${api.options.id}-msgbox {
  1021. z-index: 65535;
  1022. background-color: var(--shadow-color);
  1023. font-size: 16px;
  1024. max-width: 24em;
  1025. min-width: 2em;
  1026. color: var(--light-text-color);
  1027. padding: 0.5em 1em;
  1028. border-radius: 0.6em;
  1029. opacity: 0;
  1030. transition: opacity ${api.options.fadeTime}ms ease-in-out;
  1031. user-select: none;
  1032. }
  1033.  
  1034. .${api.options.id}-msgbox .gm-advanced-table td {
  1035. vertical-align: middle;
  1036. }
  1037. .${api.options.id}-msgbox .gm-advanced-table td:first-child {
  1038. padding-right: 0.6em;
  1039. }
  1040. `
  1041. }
  1042. }