Greasy Fork is available in English.

UserscriptAPI

My API for userscripts.

Od 22.08.2021.. Pogledajte najnovija verzija.

Ovu skriptu ne treba izravno instalirati. To je biblioteka za druge skripte koje se uključuju u meta direktivu // @require https://update.greatest.deepsurf.us/scripts/409641/962685/UserscriptAPI.js

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