UserscriptAPI

My API for userscripts.

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

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

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