UserscriptAPI

My API for userscripts.

当前为 2021-07-26 提交的版本,查看 最新版本

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

  1. /* exported UserscriptAPI */
  2. /**
  3. * UserscriptAPI
  4. *
  5. * 根据使用到的功能,可能需要通过 `@grant` 引入 `GM_xmlhttpRequest` 或 `GM_download`。
  6. *
  7. * 如无特殊说明,涉及到时间时所用单位均为毫秒。
  8. * @version 1.3.1.20210726
  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. config = {
  130. position: 'fixed',
  131. top: '50%',
  132. left: '50%',
  133. ...config,
  134. }
  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. * 获取元素绝对位置横坐标
  241. * @param {HTMLElement} el 元素
  242. */
  243. getElementLeft(el) {
  244. let left = el.offsetLeft
  245. let node = el.offsetParent
  246. while (node instanceof HTMLElement) {
  247. left += node.offsetLeft
  248. node = node.offsetParent
  249. }
  250. return left
  251. },
  252.  
  253. /**
  254. * 获取元素绝对位置纵坐标
  255. * @param {HTMLElement} el 元素
  256. */
  257. getElementTop(el) {
  258. let top = el.offsetTop
  259. let node = el.offsetParent
  260. while (node instanceof HTMLElement) {
  261. top += node.offsetTop
  262. node = node.offsetParent
  263. }
  264. return top
  265. },
  266.  
  267. /**
  268. * 判断 HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  269. * @param {HTMLElement} el 目标元素
  270. * @param {HTMLElement} [endEl] 终止元素,当搜索到该元素时终止判断(不会判断该元素)
  271. * @returns {boolean} HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  272. */
  273. isFixed(el, endEl) {
  274. while (el instanceof HTMLElement && el != endEl) {
  275. if (window.getComputedStyle(el).position == 'fixed') {
  276. return true
  277. }
  278. el = el.parentNode
  279. }
  280. return false
  281. },
  282. }
  283. /** 信息通知相关 */
  284. this.message = {
  285. /**
  286. * 创建信息
  287. * @param {string} msg 信息
  288. * @param {Object} [config] 设置
  289. * @param {boolean} [config.autoClose=true] 是否自动关闭信息,配合 `config.ms` 使用
  290. * @param {number} [config.ms=1500] 显示时间(单位:ms,不含渐显/渐隐时间)
  291. * @param {boolean} [config.html=false] 是否将 `msg` 理解为 HTML
  292. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  293. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,相当于设置为 `{ top: '70%', left: '50%' }`
  294. * @return {HTMLElement} 信息框元素
  295. */
  296. create(msg, config) {
  297. const defaultConfig = {
  298. autoClose: true,
  299. ms: 1500,
  300. html: false,
  301. width: null,
  302. position: {
  303. top: '70%',
  304. left: '50%',
  305. },
  306. }
  307. config = { ...defaultConfig, ...config }
  308.  
  309. const msgbox = document.createElement('div')
  310. msgbox.className = `${api.options.id}-msgbox`
  311. if (config.width) {
  312. msgbox.style.minWidth = 'auto' // 为什么一个是 auto 一个是 none?真是神奇的设计
  313. msgbox.style.maxWidth = 'none'
  314. msgbox.style.width = config.width
  315. }
  316. msgbox.style.display = 'block'
  317. if (config.html) {
  318. msgbox.innerHTML = msg
  319. } else {
  320. msgbox.innerText = msg
  321. }
  322. document.body.appendChild(msgbox)
  323. setTimeout(() => {
  324. api.dom.setAbsoluteCenter(msgbox, config.position)
  325. }, 10)
  326.  
  327. api.dom.fade(true, msgbox, () => {
  328. if (config.autoClose) {
  329. setTimeout(() => {
  330. this.close(msgbox)
  331. }, config.ms)
  332. }
  333. })
  334. return msgbox
  335. },
  336.  
  337. /**
  338. * 关闭信息
  339. * @param {HTMLElement} msgbox 信息框元素
  340. */
  341. close(msgbox) {
  342. if (msgbox) {
  343. api.dom.fade(false, msgbox, () => {
  344. msgbox?.remove()
  345. })
  346. }
  347. },
  348.  
  349. /**
  350. * 创建高级信息
  351. * @param {HTMLElement} el 启动元素
  352. * @param {string} msg 信息
  353. * @param {string} flag 标志信息
  354. * @param {Object} [config] 设置
  355. * @param {string} [config.flagSize='1.8em'] 标志大小
  356. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  357. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,沿用 `UserscriptAPI.message.create()` 的默认设置
  358. * @param {() => boolean} [config.disabled] 用于获取是否禁用信息的方法
  359. */
  360. advanced(el, msg, flag, config) {
  361. const defaultConfig = {
  362. flagSize: '1.8em',
  363. // 不能把数据列出,否则解构的时候会出问题
  364. }
  365. config = { ...defaultConfig, ...config }
  366.  
  367. const _self = this
  368. el.show = false
  369. el.onmouseenter = function() {
  370. if (config.disabled?.()) return
  371. const htmlMsg = `
  372. <table class="gm-advanced-table"><tr>
  373. <td style="font-size:${config.flagSize};line-height:${config.flagSize}">${flag}</td>
  374. <td>${msg}</td>
  375. </tr></table>
  376. `
  377. this.msgbox = _self.create(htmlMsg, { ...config, html: true, autoClose: false })
  378.  
  379. // 可能信息框刚好生成覆盖在 el 上,需要做一个处理
  380. this.msgbox.onmouseenter = function() {
  381. this.mouseOver = true
  382. }
  383. // 从信息框出来也会关闭信息框,防止覆盖的情况下无法关闭
  384. this.msgbox.onmouseleave = function() {
  385. _self.close(this)
  386. }
  387. }
  388. el.onmouseleave = function() {
  389. setTimeout(() => {
  390. if (this.msgbox && !this.msgbox.mouseOver) {
  391. this.msgbox.onmouseleave = null
  392. _self.close(this.msgbox)
  393. }
  394. })
  395. }
  396. },
  397.  
  398. /**
  399. * 创建提醒信息
  400. * @param {string} msg 信息
  401. */
  402. alert(msg) {
  403. alert(`${api.options.label ? `${api.options.label}\n\n` : ''}${msg}`)
  404. },
  405.  
  406. /**
  407. * 创建确认信息
  408. * @param {string} msg 信息
  409. * @returns {boolean} 用户输入
  410. */
  411. confirm(msg) {
  412. return confirm(`${api.options.label ? `${api.options.label}\n\n` : ''}${msg}`)
  413. },
  414.  
  415. /**
  416. * 创建输入提示信息
  417. * @param {string} msg 信息
  418. * @param {string} [val] 默认值
  419. * @returns {string} 用户输入
  420. */
  421. prompt(msg, val) {
  422. return prompt(`${api.options.label ? `${api.options.label}\n\n` : ''}${msg}`, val)
  423. },
  424. }
  425. /** 用于等待元素加载/条件达成再执行操作 */
  426. this.wait = {
  427. /**
  428. * 在条件达成后执行操作
  429. *
  430. * 当条件达成后,如果不存在终止条件,那么直接执行 `callback(result)`。
  431. *
  432. * 当条件达成后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否达成终止条件,称为终止条件的二次判断。如果在此期间,终止条件通过,则表示依然不达成条件,故执行 `onStop()` 而非 `callback(result)`。如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  433. *
  434. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  435. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  436. * @param {(result) => void} [options.callback] 当达成条件时执行 `callback(result)`
  437. * @param {number} [options.interval] 检测时间间隔
  438. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  439. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  440. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  441. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  442. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  443. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  444. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  445. * @param {(e) => void} [options.onError] 条件检测过程中发生错误时执行 `onError()`
  446. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  447. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  448. * @returns {() => boolean} 执行后终止检测的函数
  449. */
  450. executeAfterConditionPassed(options) {
  451. options = {
  452. ...api.options.wait.condition,
  453. ...options,
  454. }
  455. let stop = false
  456. let endTime = null
  457. if (options.timeout === 0) {
  458. endTime = 0
  459. } else {
  460. endTime = Math.max(new Date().getTime() + options.timeout - options.timePadding, 1)
  461. }
  462. const task = async () => {
  463. if (stop) return
  464. let result = null
  465. try {
  466. result = await options.condition()
  467. } catch (e) {
  468. options.onError?.call(options, e)
  469. if (options.stopOnError) {
  470. stop = true
  471. }
  472. }
  473. if (stop) return
  474. const stopResult = await options.stopCondition?.()
  475. if (stopResult) {
  476. stop = true
  477. options.onStop?.call(options)
  478. } else if (endTime !== 0 && new Date().getTime() > endTime) {
  479. if (options.stopOnTimeout) {
  480. stop = true
  481. } else {
  482. endTime = 0
  483. }
  484. options.onTimeout?.call(options)
  485. } else if (result) {
  486. stop = true
  487. if (options.stopCondition && options.stopTimeout > 0) {
  488. this.executeAfterConditionPassed({
  489. condition: options.stopCondition,
  490. callback: options.onStop,
  491. interval: options.stopInterval,
  492. timeout: options.stopTimeout,
  493. onTimeout: () => options.callback.call(options, result)
  494. })
  495. } else {
  496. options.callback.call(options, result)
  497. }
  498. }
  499. if (!stop) {
  500. setTimeout(task, options.interval)
  501. }
  502. }
  503. setTimeout(async () => {
  504. if (stop) return
  505. await task()
  506. if (stop) return
  507. setTimeout(task, options.interval)
  508. }, options.timePadding)
  509. return function() {
  510. stop = true
  511. }
  512. },
  513.  
  514. /**
  515. * 在元素加载完成后执行操作
  516. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  517. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  518. * @param {HTMLElement} [options.base] 基元素
  519. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  520. * @param {(element: HTMLElement) => void} [options.callback] 当 `element` 加载成功时执行 `callback(element)`
  521. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  522. * @param {boolean} [options.multiple] 若一次检测到多个目标元素,是否在所有元素上执行回调函数(否则只处理第一个结果)
  523. * @param {boolean} [options.repeat] `element` 加载成功后是否继续检测
  524. * @param {number} [options.throttleWait] 检测节流时间(非准确);节流控制仅当 `repeat` 为 `false` 时生效,设置为 `0` 时禁用节流控制
  525. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  526. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  527. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  528. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  529. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  530. * @param {(e) => void} [options.onError] 检测过程中发生错误时执行 `onError()`
  531. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  532. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  533. * @returns {() => boolean} 执行后终止检测的函数
  534. */
  535. executeAfterElementLoaded(options) {
  536. options = {
  537. ...api.options.wait.element,
  538. ...options,
  539. }
  540.  
  541. let loaded = false
  542. let stopped = false
  543.  
  544. const stop = () => {
  545. if (!stopped) {
  546. stopped = true
  547. ob.disconnect()
  548. }
  549. }
  550.  
  551. const isExcluded = element => {
  552. return options.exclude?.indexOf(element) >= 0
  553. }
  554.  
  555. const task = root => {
  556. let success = false
  557. if (options.multiple) {
  558. const elements = root.querySelectorAll(options.selector)
  559. if (elements.length > 0) {
  560. for (const element of elements) {
  561. if (!isExcluded(element)) {
  562. success = true
  563. options.callback.call(options, element)
  564. }
  565. }
  566. }
  567. } else {
  568. const element = root.querySelector(options.selector)
  569. if (element && !isExcluded(element)) {
  570. success = true
  571. options.callback.call(options, element)
  572. }
  573. }
  574. loaded = success || loaded
  575. return success
  576. }
  577. const singleTask = (!options.repeat && options.throttleWait > 0) ? api.tool.throttle(task, options.throttleWait) : task
  578.  
  579. const repeatTask = records => {
  580. let success = false
  581. for (const record of records) {
  582. for (const addedNode of record.addedNodes) {
  583. if (addedNode instanceof HTMLElement) {
  584. const virtualRoot = document.createElement('div')
  585. virtualRoot.appendChild(addedNode.cloneNode())
  586. const el = virtualRoot.querySelector(options.selector)
  587. if (el && !isExcluded(addedNode)) {
  588. success = true
  589. loaded = true
  590. options.callback.call(options, addedNode)
  591. if (!options.multiple) {
  592. return true
  593. }
  594. }
  595. success = task(addedNode) || success
  596. if (success && !options.multiple) {
  597. return true
  598. }
  599. }
  600. }
  601. }
  602. }
  603.  
  604. const ob = new MutationObserver(records => {
  605. try {
  606. if (stopped) {
  607. return
  608. } else if (options.stopCondition?.()) {
  609. stop()
  610. options.onStop?.call(options)
  611. return
  612. }
  613. if (options.repeat) {
  614. repeatTask(records)
  615. } else {
  616. singleTask(options.base)
  617. }
  618. if (loaded && !options.repeat) {
  619. stop()
  620. }
  621. } catch (e) {
  622. options.onError?.call(options, e)
  623. if (options.stopOnError) {
  624. stop()
  625. }
  626. }
  627. })
  628.  
  629. setTimeout(() => {
  630. try {
  631. if (!stopped) {
  632. if (options.stopCondition?.()) {
  633. stop()
  634. options.onStop?.call(options)
  635. return
  636. }
  637. task(options.base)
  638. }
  639. } catch (e) {
  640. options.onError?.call(options, e)
  641. if (options.stopOnError) {
  642. stop()
  643. }
  644. }
  645. if (!stopped) {
  646. if (!loaded || options.repeat) {
  647. ob.observe(options.base, {
  648. childList: true,
  649. subtree: options.subtree,
  650. })
  651. if (options.timeout > 0) {
  652. setTimeout(() => {
  653. if (!stopped) {
  654. if (!loaded) {
  655. if (options.stopOnTimeout) {
  656. stop()
  657. }
  658. options.onTimeout?.call(options)
  659. } else { // 只要检测到,无论重复与否,都不算超时;需永久检测必须设 timeout 为 0
  660. stop()
  661. }
  662. }
  663. }, Math.max(options.timeout - options.timePadding, 0))
  664. }
  665. }
  666. }
  667. }, options.timePadding)
  668. return stop
  669. },
  670.  
  671. /**
  672. * 等待条件达成
  673. *
  674. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  675. * @async
  676. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.condition` 填充
  677. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  678. * @param {number} [options.interval] 检测时间间隔
  679. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  680. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  681. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  682. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  683. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  684. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  685. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  686. * @returns {Promise} `result`
  687. * @throws 等待超时、达成终止条件、等待错误时抛出
  688. * @see executeAfterConditionPassed
  689. */
  690. async waitForConditionPassed(options) {
  691. return new Promise((resolve, reject) => {
  692. this.executeAfterConditionPassed({
  693. ...options,
  694. callback: result => resolve(result),
  695. onTimeout: function() {
  696. const error = ['TIMEOUT', 'waitForConditionPassed', this]
  697. if (this.stopOnTimeout) {
  698. reject(error)
  699. } else {
  700. api.logger.warn(error)
  701. }
  702. },
  703. onStop: function() {
  704. reject(['STOP', 'waitForConditionPassed', this])
  705. },
  706. onError: function(e) {
  707. reject(['ERROR', 'waitForConditionPassed', this, e])
  708. },
  709. })
  710. })
  711. },
  712.  
  713. /**
  714. * 等待元素加载完成
  715. *
  716. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  717. * @async
  718. * @param {Object} options 选项;缺失选项用 `UserscriptAPI.options.wait.element` 填充
  719. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  720. * @param {HTMLElement} [options.base] 基元素
  721. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  722. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  723. * @param {number} [options.throttleWait] 检测节流时间(非准确);节流控制仅当 `repeat` 为 `false` 时生效,设置为 `0` 时禁用节流控制
  724. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  725. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  726. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  727. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  728. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  729. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  730. * @returns {Promise<HTMLElement>} `element`
  731. * @throws 等待超时、达成终止条件、等待错误时抛出
  732. * @see executeAfterElementLoaded
  733. */
  734. async waitForElementLoaded(options) {
  735. return new Promise((resolve, reject) => {
  736. this.executeAfterElementLoaded({
  737. ...options,
  738. callback: element => resolve(element),
  739. onTimeout: function() {
  740. const error = ['TIMEOUT', 'waitForElementLoaded', this]
  741. if (this.stopOnTimeout) {
  742. reject(error)
  743. } else {
  744. api.logger.warn(error)
  745. }
  746. },
  747. onStop: function() {
  748. reject(['STOP', 'waitForElementLoaded', this])
  749. },
  750. onError: function() {
  751. reject(['ERROR', 'waitForElementLoaded', this])
  752. },
  753. })
  754. })
  755. },
  756.  
  757. /**
  758. * 元素加载选择器
  759. *
  760. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  761. * @async
  762. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  763. * @param {HTMLElement} [base=UserscriptAPI.options.wait.element.base] 基元素
  764. * @param {boolean} [stopOnTimeout=UserscriptAPI.options.wait.element.stopOnTimeout] 检测超时时是否终止检测
  765. * @returns {Promise<HTMLElement>} `element`
  766. * @throws 等待超时、达成终止条件、等待错误时抛出
  767. * @see executeAfterElementLoaded
  768. */
  769. async waitQuerySelector(selector, base = api.options.wait.element.base, stopOnTimeout = api.options.wait.element.stopOnTimeout) {
  770. return new Promise((resolve, reject) => {
  771. this.executeAfterElementLoaded({
  772. ... { selector, base, stopOnTimeout },
  773. callback: element => resolve(element),
  774. onTimeout: function() {
  775. const error = ['TIMEOUT', 'waitQuerySelector', this]
  776. if (this.stopOnTimeout) {
  777. reject(error)
  778. } else {
  779. api.logger.warn(error)
  780. }
  781. },
  782. onStop: function() {
  783. reject(['STOP', 'waitQuerySelector', this])
  784. },
  785. onError: function() {
  786. reject(['ERROR', 'waitQuerySelector', this])
  787. },
  788. })
  789. })
  790. },
  791. }
  792. /** 网络相关 */
  793. this.web = {
  794. /** @typedef {Object} GM_xmlhttpRequest_details */
  795. /** @typedef {Object} GM_xmlhttpRequest_response */
  796. /**
  797. * 发起网络请求
  798. * @async
  799. * @param {GM_xmlhttpRequest_details} details 定义及细节同 {@link GM_xmlhttpRequest} 的 `details`
  800. * @returns {Promise<GM_xmlhttpRequest_response>} 响应对象
  801. * @throws 等待超时、达成终止条件、等待错误时抛出
  802. * @see {@link https://www.tampermonkey.net/documentation.php#GM_xmlhttpRequest GM_xmlhttpRequest}
  803. */
  804. async request(details) {
  805. if (details) {
  806. return new Promise((resolve, reject) => {
  807. const throwHandler = function(msg) {
  808. api.logger.error('NETWORK REQUEST ERROR')
  809. reject(msg)
  810. }
  811. details.onerror = details.onerror ?? (() => throwHandler(['ERROR', 'request', details]))
  812. details.ontimeout = details.ontimeout ?? (() => throwHandler(['TIMEOUT', 'request', details]))
  813. details.onload = details.onload ?? (response => resolve(response))
  814. GM_xmlhttpRequest(details)
  815. })
  816. }
  817. },
  818.  
  819. /** @typedef {Object} GM_download_details */
  820. /**
  821. * 下载资源
  822. * @param {GM_download_details} details 定义及细节同 {@link GM_download} 的 `details`
  823. * @returns {() => void} 用于终止下载的方法
  824. * @see {@link https://www.tampermonkey.net/documentation.php#GM_download GM_download}
  825. */
  826. download(details) {
  827. if (details) {
  828. try {
  829. const cfg = { ...details }
  830. let name = cfg.name
  831. if (name.indexOf('.') > -1) {
  832. let parts = cfg.url.split('/')
  833. const last = parts[parts.length - 1].split('?')[0]
  834. if (last.indexOf('.') > -1) {
  835. parts = last.split('.')
  836. name = `${name}.${parts[parts.length - 1]}`
  837. } else {
  838. name = name.replaceAll('.', '_')
  839. }
  840. cfg.name = name
  841. }
  842. if (!cfg.onerror) {
  843. cfg.onerror = function(error, details) {
  844. api.logger.error('DOWNLOAD ERROR')
  845. api.logger.error([error, details])
  846. }
  847. }
  848. if (!cfg.ontimeout) {
  849. cfg.ontimeout = function() {
  850. api.logger.error('DOWNLOAD TIMEOUT')
  851. }
  852. }
  853. GM_download(cfg)
  854. } catch (e) {
  855. api.logger.error('DOWNLOAD ERROR')
  856. api.logger.error(e)
  857. }
  858. }
  859. return () => {}
  860. },
  861.  
  862. /**
  863. * 判断给定 URL 是否匹配
  864. * @param {RegExp | RegExp[]} reg 用于判断是否匹配的正则表达式,或正则表达式数组
  865. * @param {'SINGLE' | 'AND' | 'OR'} [mode='SINGLE'] 匹配模式
  866. * @returns {boolean} 是否匹配
  867. */
  868. urlMatch(reg, mode = 'SINGLE') {
  869. let result = false
  870. const href = location.href
  871. if (mode == 'SINGLE') {
  872. if (reg instanceof Array) {
  873. if (reg.length > 0) {
  874. reg = reg[0]
  875. } else {
  876. reg = null
  877. }
  878. }
  879. if (reg) {
  880. result = reg.test(href)
  881. }
  882. } else {
  883. if (!(reg instanceof Array)) {
  884. reg = [reg]
  885. }
  886. if (reg.length > 0) {
  887. if (mode == 'AND') {
  888. result = true
  889. for (const r of reg) {
  890. if (!r.test(href)) {
  891. result = false
  892. break
  893. }
  894. }
  895. } else if (mode == 'OR') {
  896. for (const r of reg) {
  897. if (r.test(href)) {
  898. result = true
  899. break
  900. }
  901. }
  902. }
  903. }
  904. }
  905. return result
  906. },
  907. }
  908. /**
  909. * 日志
  910. */
  911. this.logger = {
  912. /**
  913. * 打印格式化日志
  914. * @param {*} message 日志信息
  915. * @param {string} label 日志标签
  916. * @param {'info', 'warn', 'error'} [level] 日志等级
  917. */
  918. log(message, label, level = 'info') {
  919. const output = console[level == 'info' ? 'log' : level]
  920. const type = typeof message == 'string' ? '%s' : '%o'
  921. output(`%c${label}%c${type}`, logCss, '', message)
  922. },
  923.  
  924. /**
  925. * 打印日志
  926. * @param {*} message 日志信息
  927. */
  928. info(message) {
  929. if (message === undefined) {
  930. message = '[undefined]'
  931. } else if (message === null) {
  932. message = '[null]'
  933. } else if (message === '') {
  934. message = '[empty string]'
  935. }
  936. if (api.options.label) {
  937. this.log(message, api.options.label)
  938. } else {
  939. console.log(message)
  940. }
  941. },
  942.  
  943. /**
  944. * 打印警告日志
  945. * @param {*} message 警告日志信息
  946. */
  947. warn(message) {
  948. if (message === undefined) {
  949. message = '[undefined]'
  950. } else if (message === null) {
  951. message = '[null]'
  952. } else if (message === '') {
  953. message = '[empty string]'
  954. }
  955. if (api.options.label) {
  956. this.log(message, api.options.label, 'warn')
  957. } else {
  958. console.warn(message)
  959. }
  960. },
  961.  
  962. /**
  963. * 打印错误日志
  964. * @param {*} message 错误日志信息
  965. */
  966. error(message) {
  967. if (message === undefined) {
  968. message = '[undefined]'
  969. } else if (message === null) {
  970. message = '[null]'
  971. } else if (message === '') {
  972. message = '[empty string]'
  973. }
  974. if (api.options.label) {
  975. this.log(message, api.options.label, 'error')
  976. } else {
  977. console.error(message)
  978. }
  979. },
  980. }
  981. /**
  982. * 工具
  983. */
  984. this.tool = {
  985. /**
  986. * 生成消抖函数
  987. * @param {Function} fn 目标函数
  988. * @param {number} [wait=0] 消抖延迟
  989. * @param {Object} [options] 选项
  990. * @param {boolean} [options.leading] 是否在延迟开始前调用目标函数
  991. * @param {boolean} [options.trailing=true] 是否在延迟结束后调用目标函数
  992. * @param {number} [options.maxWait=0] 最大延迟时间(非准确),`0` 表示禁用
  993. * @returns {Function} 消抖函数 `debounced`,可调用 `debounced.cancel()` 取消执行
  994. */
  995. debounce(fn, wait = 0, options = {}) {
  996. options = {
  997. leading: false,
  998. trailing: true,
  999. maxWait: 0,
  1000. ...options,
  1001. }
  1002.  
  1003. let tid = null
  1004. let start = null
  1005. let execute = null
  1006. let callback = null
  1007.  
  1008. function debounced() {
  1009. execute = () => {
  1010. fn.apply(this, arguments)
  1011. execute = null
  1012. }
  1013. callback = () => {
  1014. if (options.trailing) {
  1015. execute?.()
  1016. }
  1017. tid = null
  1018. start = null
  1019. }
  1020.  
  1021. if (tid) {
  1022. clearTimeout(tid)
  1023. if (options.maxWait > 0 && new Date().getTime() - start > options.maxWait) {
  1024. callback()
  1025. }
  1026. }
  1027.  
  1028. if (!tid && options.leading) {
  1029. execute?.()
  1030. }
  1031.  
  1032. if (!start) {
  1033. start = new Date().getTime()
  1034. }
  1035.  
  1036. tid = setTimeout(callback, wait)
  1037. }
  1038.  
  1039. debounced.cancel = function() {
  1040. if (tid) {
  1041. clearTimeout(tid)
  1042. tid = null
  1043. start = null
  1044. }
  1045. }
  1046.  
  1047. return debounced
  1048. },
  1049.  
  1050. /**
  1051. * 生成节流函数
  1052. * @param {Function} fn 目标函数
  1053. * @param {number} [wait=0] 节流延迟(非准确)
  1054. * @returns {Function} 节流函数 `throttled`,可调用 `throttled.cancel()` 取消执行
  1055. */
  1056. throttle(fn, wait = 0) {
  1057. return this.debounce(fn, wait, {
  1058. leading: true,
  1059. trailing: true,
  1060. maxWait: wait,
  1061. })
  1062. },
  1063. }
  1064.  
  1065. api.wait.waitQuerySelector('head').then(head => {
  1066. const css = head.appendChild(document.createElement('style'))
  1067. css.id = `_api_${api.options.id}-css`
  1068. css.setAttribute('type', 'text/css')
  1069. css.innerHTML = `
  1070. :root {
  1071. --light-text-color: white;
  1072. --shadow-color: #000000bf;
  1073. }
  1074. .${api.options.id}-msgbox {
  1075. z-index: 65535;
  1076. background-color: var(--shadow-color);
  1077. font-size: 16px;
  1078. max-width: 24em;
  1079. min-width: 2em;
  1080. color: var(--light-text-color);
  1081. padding: 0.5em 1em;
  1082. border-radius: 0.6em;
  1083. opacity: 0;
  1084. transition: opacity ${api.options.fadeTime}ms ease-in-out;
  1085. user-select: none;
  1086. }
  1087. .${api.options.id}-msgbox .gm-advanced-table td {
  1088. vertical-align: middle;
  1089. }
  1090. .${api.options.id}-msgbox .gm-advanced-table td:first-child {
  1091. padding-right: 0.6em;
  1092. }
  1093. `
  1094. })
  1095. }
  1096. }