Greasy Fork is available in English.

UserscriptAPI

My API for userscripts.

As of 10.08.2021. See ბოლო ვერსია.

ეს სკრიპტი არ უნდა იყოს პირდაპირ დაინსტალირებული. ეს ბიბლიოთეკაა, სხვა სკრიპტებისთვის უნდა ჩართეთ მეტა-დირექტივაში // @require https://update.greatest.deepsurf.us/scripts/409641/958946/UserscriptAPI.js.

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