UserscriptAPI

My API for userscripts.

Fra 07.08.2021. Se den seneste versjonen.

Dette scriptet burde ikke installeres direkte. Det er et bibliotek for andre script å inkludere med det nye metadirektivet // @require https://update.greatest.deepsurf.us/scripts/409641/958042/UserscriptAPI.js

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