UserscriptAPI

My API for userscripts.

当前为 2021-08-11 提交的版本,查看 最新版本

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

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