UserscriptAPI

My API for userscripts.

As of 2021-08-31. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/409641/965951/UserscriptAPI.js

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