UserscriptAPI

My API for userscripts.

当前为 2021-09-01 提交的版本,查看 最新版本

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

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