UserscriptAPI

My API for userscripts.

As of 2021-08-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/409641/957714/UserscriptAPI.js

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