UserscriptAPI

My API for userscripts.

目前為 2021-06-24 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/409641/943615/UserscriptAPI.js

  1. /* exported API */
  2. /**
  3. * API
  4. * @author Laster2800
  5. */
  6. class API {
  7. /**
  8. * @param {Object} [options] 选项
  9. * @param {string} [options.id='_0'] 标识符
  10. * @param {string} [options.label] 日志标签,为空时不设置标签
  11. * @param {number} [options.waitInterval=100] `wait` API 默认 `options.interval`
  12. * @param {number} [options.waitTimeout=6000] `wait` API 默认 `options.timeout`
  13. * @param {number} [options.fadeTime=400] UI 渐变时间(单位:ms)
  14. */
  15. constructor(options) {
  16. const defaultOptions = {
  17. id: '_0',
  18. label: null,
  19. waitInterval: 100,
  20. waitTimeout: 6000,
  21. fadeTime: 400,
  22. }
  23. this.options = {
  24. ...defaultOptions,
  25. ...options,
  26. }
  27.  
  28. const original = window[`_api_${this.options.id}`]
  29. if (original) {
  30. original.options = this.options
  31. return original
  32. }
  33. window[`_api_${this.options.id}`] = this
  34.  
  35. const api = this
  36. const logCss = `
  37. background-color: black;
  38. color: white;
  39. border-radius: 2px;
  40. padding: 2px;
  41. margin-right: 2px;
  42. `
  43.  
  44. /** DOM 相关 */
  45. this.dom = {
  46. /**
  47. * 创建 locationchange 事件
  48. * @see {@link https://stackoverflow.com/a/52809105 How to detect if URL has changed after hash in JavaScript}
  49. */
  50. createLocationchangeEvent() {
  51. if (!unsafeWindow._createLocationchangeEvent) {
  52. history.pushState = (f => function pushState() {
  53. const ret = f.apply(this, arguments)
  54. window.dispatchEvent(new Event('pushstate'))
  55. window.dispatchEvent(new Event('locationchange'))
  56. return ret
  57. })(history.pushState)
  58. history.replaceState = (f => function replaceState() {
  59. const ret = f.apply(this, arguments)
  60. window.dispatchEvent(new Event('replacestate'))
  61. window.dispatchEvent(new Event('locationchange'))
  62. return ret
  63. })(history.replaceState)
  64. window.addEventListener('popstate', () => {
  65. window.dispatchEvent(new Event('locationchange'))
  66. })
  67. unsafeWindow._createLocationchangeEvent = true
  68. }
  69. },
  70.  
  71. /**
  72. * 将一个元素绝对居中
  73. *
  74. * 要求该元素此时可见且尺寸为确定值(一般要求为块状元素)。运行后会在 `target` 上附加 `_absoluteCenter` 方法,若该方法已存在,则无视 `config` 直接执行 `target._absoluteCenter()`。
  75. * @param {HTMLElement} target 目标元素
  76. * @param {Object} [config] 配置
  77. * @param {string} [config.position='fixed'] 定位方式
  78. * @param {string} [config.top='50%'] `style.top`
  79. * @param {string} [config.left='50%'] `style.left`
  80. */
  81. setAbsoluteCenter(target, config) {
  82. if (!target._absoluteCenter) {
  83. const defaultConfig = {
  84. position: 'fixed',
  85. top: '50%',
  86. left: '50%',
  87. }
  88. config = { ...defaultConfig, ...config }
  89. target._absoluteCenter = () => {
  90. const style = getComputedStyle(target)
  91. const top = (parseFloat(style.height) + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)) / 2
  92. const left = (parseFloat(style.width) + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight)) / 2
  93. target.style.top = `calc(${config.top} - ${top}px)`
  94. target.style.left = `calc(${config.left} - ${left}px)`
  95. target.style.position = config.position
  96. }
  97.  
  98. // 实现一个简单的 debounce 来响应 resize 事件
  99. let tid
  100. window.addEventListener('resize', function() {
  101. if (target && target._absoluteCenter) {
  102. if (tid) {
  103. clearTimeout(tid)
  104. tid = null
  105. }
  106. tid = setTimeout(() => {
  107. target._absoluteCenter()
  108. }, 500)
  109. }
  110. })
  111. }
  112. target._absoluteCenter()
  113. },
  114.  
  115. /**
  116. * 处理 HTML 元素的渐显和渐隐
  117. * @param {boolean} inOut 渐显/渐隐
  118. * @param {HTMLElement} target HTML 元素
  119. * @param {() => void} [callback] 处理完成的回调函数
  120. */
  121. fade(inOut, target, callback) {
  122. // fadeId 等同于当前时间戳,其意义在于保证对于同一元素,后执行的操作必将覆盖前的操作
  123. const fadeId = new Date().getTime()
  124. target._fadeId = fadeId
  125. if (inOut) { // 渐显
  126. // 只有 display 可视情况下修改 opacity 才会触发 transition
  127. if (getComputedStyle(target).display == 'none') {
  128. target.style.display = 'unset'
  129. }
  130. setTimeout(() => {
  131. let success = false
  132. if (target._fadeId <= fadeId) {
  133. target.style.opacity = '1'
  134. success = true
  135. }
  136. callback && callback(success)
  137. }, 10) // 此处的 10ms 是为了保证修改 display 后在浏览器上真正生效,按 HTML5 定义,浏览器需保证 display 在修改 4ms 后保证生效,但实际上大部分浏览器貌似做不到,等个 10ms 再修改 opacity
  138. } else { // 渐隐
  139. target.style.opacity = '0'
  140. setTimeout(() => {
  141. let success = false
  142. if (target._fadeId <= fadeId) {
  143. target.style.display = 'none'
  144. success = true
  145. }
  146. callback && callback(success)
  147. }, api.options.fadeTime)
  148. }
  149. },
  150.  
  151. /**
  152. * 为 HTML 元素添加 `class`
  153. * @param {HTMLElement} el 目标元素
  154. * @param {string} className `class`
  155. */
  156. addClass(el, className) {
  157. if (el instanceof HTMLElement) {
  158. if (!el.className) {
  159. el.className = className
  160. } else {
  161. const clz = el.className.split(' ')
  162. if (clz.indexOf(className) < 0) {
  163. clz.push(className)
  164. el.className = clz.join(' ')
  165. }
  166. }
  167. }
  168. },
  169.  
  170. /**
  171. * 为 HTML 元素移除 `class`
  172. * @param {HTMLElement} el 目标元素
  173. * @param {string} [className] `class`,未指定时移除所有 `class`
  174. */
  175. removeClass(el, className) {
  176. if (el instanceof HTMLElement) {
  177. if (typeof className == 'string') {
  178. if (el.className == className) {
  179. el.className = ''
  180. } else {
  181. let clz = el.className.split(' ')
  182. clz = clz.reduce((prev, current) => {
  183. if (current != className) {
  184. prev.push(current)
  185. }
  186. return prev
  187. }, [])
  188. el.className = clz.join(' ')
  189. }
  190. } else {
  191. el.className = ''
  192. }
  193. }
  194. },
  195.  
  196. /**
  197. * 判断 HTML 元素类名中是否含有 `class`
  198. * @param {HTMLElement|{className: string}} el 目标元素
  199. * @param {string|string[]} className `class`,支持同时判断多个
  200. * @param {boolean} [and] 同时判断多个 `class` 时,默认采取 `OR` 逻辑,是否采用 `AND` 逻辑
  201. * @returns {boolean} 是否含有 `class`
  202. */
  203. containsClass(el, className, and = false) {
  204. if (el instanceof HTMLElement || typeof el.className == 'string') {
  205. if (el.className == className) {
  206. return true
  207. } else {
  208. const clz = el.className.split(' ')
  209. if (className instanceof Array) {
  210. if (and) {
  211. for (const c of className) {
  212. if (clz.indexOf(c) < 0) {
  213. return false
  214. }
  215. }
  216. return true
  217. } else {
  218. for (const c of className) {
  219. if (clz.indexOf(c) >= 0) {
  220. return true
  221. }
  222. }
  223. return false
  224. }
  225. } else {
  226. return clz.indexOf(className) >= 0
  227. }
  228. }
  229. }
  230. return false
  231. },
  232.  
  233. /**
  234. * 判断 HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  235. * @param {HTMLElement} el 目标元素
  236. * @param {HTMLElement} [endEl] 终止元素,当搜索到该元素时终止判断(不会判断该元素)
  237. * @returns {boolean} HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  238. */
  239. isFixed(el, endEl) {
  240. while (el instanceof HTMLElement && el != endEl) {
  241. if (window.getComputedStyle(el).position == 'fixed') {
  242. return true
  243. }
  244. el = el.parentNode
  245. }
  246. return false
  247. },
  248. }
  249. /** 信息通知相关 */
  250. this.message = {
  251. /**
  252. * 创建信息
  253. * @param {string} msg 信息
  254. * @param {Object} [config] 设置
  255. * @param {boolean} [config.autoClose=true] 是否自动关闭信息,配合 `config.ms` 使用
  256. * @param {number} [config.ms=1500] 显示时间(单位:ms,不含渐显/渐隐时间)
  257. * @param {boolean} [config.html=false] 是否将 `msg` 理解为 HTML
  258. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  259. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,相当于设置为 `{ top: '70%', left: '50%' }`
  260. * @return {HTMLElement} 信息框元素
  261. */
  262. create(msg, config) {
  263. const defaultConfig = {
  264. autoClose: true,
  265. ms: 1500,
  266. html: false,
  267. width: null,
  268. position: {
  269. top: '70%',
  270. left: '50%',
  271. },
  272. }
  273. config = { ...defaultConfig, ...config }
  274.  
  275. const msgbox = document.body.appendChild(document.createElement('div'))
  276. msgbox.className = `${api.options.id}-msgbox`
  277. if (config.width) {
  278. msgbox.style.minWidth = 'auto' // 为什么一个是 auto 一个是 none?真是神奇的设计
  279. msgbox.style.maxWidth = 'none'
  280. msgbox.style.width = config.width
  281. }
  282.  
  283. msgbox.style.display = 'block'
  284. setTimeout(() => {
  285. api.dom.setAbsoluteCenter(msgbox, config.position)
  286. }, 10)
  287.  
  288. if (config.html) {
  289. msgbox.innerHTML = msg
  290. } else {
  291. msgbox.innerText = msg
  292. }
  293. api.dom.fade(true, msgbox, () => {
  294. if (config.autoClose) {
  295. setTimeout(() => {
  296. this.close(msgbox)
  297. }, config.ms)
  298. }
  299. })
  300. return msgbox
  301. },
  302.  
  303. /**
  304. * 关闭信息
  305. * @param {HTMLElement} msgbox 信息框元素
  306. */
  307. close(msgbox) {
  308. if (msgbox) {
  309. api.dom.fade(false, msgbox, () => {
  310. msgbox && msgbox.remove()
  311. })
  312. }
  313. },
  314.  
  315. /**
  316. * 创建高级信息
  317. * @param {HTMLElement} el 启动元素
  318. * @param {string} msg 信息
  319. * @param {string} flag 标志信息
  320. * @param {Object} [config] 设置
  321. * @param {string} [config.flagSize='1.8em'] 标志大小
  322. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  323. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,沿用 `API.message.create()` 的默认设置
  324. * @param {() => boolean} [config.disabled] 是否处于禁用状态
  325. */
  326. advanced(el, msg, flag, config) {
  327. const defaultConfig = {
  328. flagSize: '1.8em',
  329. // 不能把数据列出,否则解构的时候会出问题
  330. }
  331. config = { ...defaultConfig, ...config }
  332.  
  333. const _self = this
  334. el.show = false
  335. el.onmouseenter = function() {
  336. if (config.disabled && config.disabled()) {
  337. return
  338. }
  339.  
  340. const htmlMsg = `
  341. <table class="gm-advanced-table"><tr>
  342. <td style="font-size:${config.flagSize};line-height:${config.flagSize}">${flag}</td>
  343. <td>${msg}</td>
  344. </tr></table>
  345. `
  346. this.msgbox = _self.create(htmlMsg, { ...config, html: true, autoClose: false })
  347.  
  348. // 可能信息框刚好生成覆盖在 el 上,需要做一个处理
  349. this.msgbox.onmouseenter = function() {
  350. this.mouseOver = true
  351. }
  352. // 从信息框出来也会关闭信息框,防止覆盖的情况下无法关闭
  353. this.msgbox.onmouseleave = function() {
  354. _self.close(this)
  355. }
  356. }
  357. el.onmouseleave = function() {
  358. setTimeout(() => {
  359. if (this.msgbox && !this.msgbox.mouseOver) {
  360. this.msgbox.onmouseleave = null
  361. _self.close(this.msgbox)
  362. }
  363. })
  364. }
  365. },
  366. }
  367. /** 用于等待元素加载/条件达成再执行操作 */
  368. this.wait = {
  369. /**
  370. * 在条件满足后执行操作
  371. *
  372. * 当条件满足后,如果不存在终止条件,那么直接执行 `callback(result)`。
  373. *
  374. * 当条件满足后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否满足终止条件,称为终止条件的二次判断。
  375. * 如果在此期间,终止条件通过,则表示依然不满足条件,故执行 `onStop()` 而非 `callback(result)`。
  376. * 如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  377. *
  378. * @param {Object} options 选项
  379. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时满足条件
  380. * @param {(result) => void} [options.callback] 当满足条件时执行 `callback(result)`
  381. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  382. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  383. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  384. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  385. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  386. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  387. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  388. * @param {(e) => void} [options.onError] 条件检测过程中发生错误时执行 `onError()`
  389. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  390. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  391. * @returns {() => boolean} 执行后终止检测的函数
  392. */
  393. executeAfterConditionPassed(options) {
  394. const defaultOptions = {
  395. callback: result => api.logger.info(result),
  396. interval: api.options.waitInterval,
  397. timeout: api.options.waitTimeout,
  398. onTimeout: null,
  399. stopCondition: null,
  400. onStop: null,
  401. stopInterval: 50,
  402. stopTimeout: 0,
  403. stopOnError: false,
  404. timePadding: 0,
  405. }
  406. options = {
  407. ...defaultOptions,
  408. ...options,
  409. }
  410.  
  411. let tid
  412. let stop = false
  413. let cnt = 0
  414. let maxCnt
  415. if (options.timeout === 0) {
  416. maxCnt = 0
  417. } else {
  418. maxCnt = (options.timeout - options.timePadding) / options.interval
  419. }
  420. const task = async () => {
  421. let result = null
  422. try {
  423. result = await options.condition()
  424. } catch (e) {
  425. options.onError && options.onError.call(options, e)
  426. if (options.stopOnError) {
  427. clearInterval(tid)
  428. }
  429. }
  430. const stopResult = options.stopCondition && await options.stopCondition()
  431. if (stop) {
  432. clearInterval(tid)
  433. } else if (stopResult) {
  434. clearInterval(tid)
  435. options.onStop && options.onStop.call(options)
  436. } else if (maxCnt !== 0 && ++cnt > maxCnt) {
  437. clearInterval(tid)
  438. options.onTimeout && options.onTimeout.call(options)
  439. } else if (result) {
  440. clearInterval(tid)
  441. if (options.stopCondition && options.stopTimeout > 0) {
  442. this.executeAfterConditionPassed({
  443. condition: options.stopCondition,
  444. callback: options.onStop,
  445. interval: options.stopInterval,
  446. timeout: options.stopTimeout,
  447. onTimeout: () => options.callback.call(options, result)
  448. })
  449. } else {
  450. options.callback.call(options, result)
  451. }
  452. }
  453. }
  454. setTimeout(() => {
  455. tid = setInterval(task, options.interval)
  456. task()
  457. }, options.timePadding)
  458. return function() {
  459. stop = true
  460. }
  461. },
  462.  
  463. /**
  464. * 在元素加载完成后执行操作
  465. *
  466. * 当条件满足后,如果不存在终止条件,那么直接执行 `callback(element)`。
  467. *
  468. * 当条件满足后,如果存在终止条件,且 `stopTimeout` 大于 `0`,则还会在接下来的 `stopTimeout` 时间内判断是否满足终止条件,称为终止条件的二次判断。
  469. * 如果在此期间,终止条件通过,则表示依然不满足条件,故执行 `onStop()` 而非 `callback(element)`。
  470. * 如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(element)`。
  471. *
  472. * @param {Object} options 选项
  473. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  474. * @param {HTMLElement} [options.base=document] 基元素
  475. * @param {(element: HTMLElement) => void} [options.callback] 当 `element` 加载成功时执行 `callback(element)`
  476. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  477. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  478. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  479. * @param {string|(() => *)} [options.stopCondition] 终止条件。若为函数,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测;若为字符串,则作为元素选择器指定终止元素 `stopElement`,若该元素加载成功则终止检测
  480. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  481. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  482. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  483. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  484. * @returns {() => boolean} 执行后终止检测的函数
  485. */
  486. executeAfterElementLoaded(options) {
  487. const defaultOptions = {
  488. base: document,
  489. callback: el => api.logger.info(el),
  490. interval: 100,
  491. timeout: 5000,
  492. onTimeout: null,
  493. stopCondition: null,
  494. onStop: null,
  495. stopInterval: 50,
  496. stopTimeout: 0,
  497. timePadding: 0,
  498. }
  499. options = {
  500. ...defaultOptions,
  501. ...options,
  502. }
  503. return this.executeAfterConditionPassed({
  504. ...options,
  505. condition: () => options.base.querySelector(options.selector),
  506. stopCondition: () => {
  507. if (options.stopCondition) {
  508. if (options.stopCondition) {
  509. return options.stopCondition()
  510. } else if (typeof options.stopCondition == 'string') {
  511. return document.querySelector(options.stopCondition)
  512. }
  513. }
  514. },
  515. })
  516. },
  517.  
  518. /**
  519. * 等待条件满足
  520. *
  521. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  522. * @async
  523. * @see executeAfterConditionPassed
  524. * @param {Object} options 选项
  525. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时满足条件
  526. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  527. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  528. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  529. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  530. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  531. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  532. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  533. * @returns {Promise} `result`
  534. * @throws 当等待超时或者被终止时抛出
  535. */
  536. async waitForConditionPassed(options) {
  537. return new Promise((resolve, reject) => {
  538. this.executeAfterConditionPassed({
  539. ...options,
  540. callback: result => resolve(result),
  541. onTimeout: function() {
  542. reject(['TIMEOUT', 'waitForConditionPassed', this])
  543. },
  544. onStop: function() {
  545. reject(['STOP', 'waitForConditionPassed', this])
  546. },
  547. onError: function(e) {
  548. reject(['ERROR', 'waitForConditionPassed', this, e])
  549. },
  550. })
  551. })
  552. },
  553.  
  554. /**
  555. * 等待元素加载
  556. *
  557. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  558. * @async
  559. * @see executeAfterElementLoaded
  560. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  561. * @param {HTMLElement} [base=document] 基元素
  562. * @returns {Promise<HTMLElement>} `element`
  563. * @throws 当等待超时或者被终止时抛出
  564. */
  565. /**
  566. * 等待元素加载
  567. *
  568. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  569. * @async
  570. * @see executeAfterElementLoaded
  571. * @param {Object} options 选项
  572. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  573. * @param {HTMLElement} [options.base=document] 基元素
  574. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  575. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  576. * @param {string|(() => *)} [options.stopCondition] 终止条件。若为函数,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测;若为字符串,则作为元素选择器指定终止元素 `stopElement`,若该元素加载成功则终止检测
  577. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  578. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  579. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  580. * @returns {Promise<HTMLElement>} `element`
  581. * @throws 当等待超时或者被终止时抛出
  582. */
  583. async waitForElementLoaded() {
  584. let options
  585. if (arguments.length > 0) {
  586. if (typeof arguments[0] == 'string') {
  587. options = { selector: arguments[0] }
  588. if (arguments[1]) {
  589. options.base = arguments[1]
  590. }
  591. } else {
  592. options = arguments[0]
  593. }
  594. }
  595. return new Promise((resolve, reject) => {
  596. this.executeAfterElementLoaded({
  597. ...options,
  598. callback: element => resolve(element),
  599. onTimeout: function() {
  600. reject(['TIMEOUT', 'waitForElementLoaded', this])
  601. },
  602. onStop: function() {
  603. reject(['STOP', 'waitForElementLoaded', this])
  604. },
  605. })
  606. })
  607. },
  608. }
  609. /** 网络相关 */
  610. this.web = {
  611. /** @typedef {Object} GM_xmlhttpRequest_details */
  612. /** @typedef {Object} GM_xmlhttpRequest_response */
  613. /**
  614. * 发起网络请求
  615. * @async
  616. * @param {GM_xmlhttpRequest_details} details 定义及细节同 {@link GM_xmlhttpRequest} 的 `details`
  617. * @returns {Promise<GM_xmlhttpRequest_response>} 响应对象
  618. * @throws 当请求发生错误或者超时时抛出
  619. * @see {@link https://www.tampermonkey.net/documentation.php#GM_xmlhttpRequest GM_xmlhttpRequest}
  620. */
  621. async request(details) {
  622. if (details) {
  623. return new Promise((resolve, reject) => {
  624. const throwHandler = function(msg) {
  625. api.logger.error('NETWORK REQUEST ERROR')
  626. reject(msg)
  627. }
  628. details.onerror = details.onerror || (() => throwHandler(['ERROR', 'request', details]))
  629. details.ontimeout = details.ontimeout || (() => throwHandler(['TIMEOUT', 'request', details]))
  630. details.onload = details.onload || (response => resolve(response))
  631. GM_xmlhttpRequest(details)
  632. })
  633. }
  634. },
  635.  
  636. /** @typedef {Object} GM_download_details */
  637. /**
  638. * 下载资源
  639. * @param {GM_download_details} details 定义及细节同 {@link GM_download} 的 `details`
  640. * @returns {() => void} 用于终止下载的方法
  641. * @see {@link https://www.tampermonkey.net/documentation.php#GM_download GM_download}
  642. */
  643. download(details) {
  644. if (details) {
  645. try {
  646. const cfg = { ...details }
  647. let name = cfg.name
  648. if (name.indexOf('.') > -1) {
  649. let parts = cfg.url.split('/')
  650. const last = parts[parts.length - 1].split('?')[0]
  651. if (last.indexOf('.') > -1) {
  652. parts = last.split('.')
  653. name = `${name}.${parts[parts.length - 1]}`
  654. } else {
  655. name = name.replaceAll('.', '_')
  656. }
  657. cfg.name = name
  658. }
  659. if (!cfg.onerror) {
  660. cfg.onerror = function(error, details) {
  661. api.logger.error('DOWNLOAD ERROR')
  662. api.logger.error([error, details])
  663. }
  664. }
  665. if (!cfg.ontimeout) {
  666. cfg.ontimeout = function() {
  667. api.logger.error('DOWNLOAD TIMEOUT')
  668. }
  669. }
  670. GM_download(cfg)
  671. } catch (e) {
  672. api.logger.error('DOWNLOAD ERROR')
  673. api.logger.error(e)
  674. }
  675. }
  676. return () => {}
  677. },
  678.  
  679. /**
  680. * 判断给定 URL 是否匹配
  681. * @param {RegExp|RegExp[]} reg 用于判断是否匹配的正则表达式,或正则表达式数组
  682. * @param {'SINGLE'|'AND'|'OR'} [mode='SINGLE'] 匹配模式
  683. * @returns {boolean} 是否匹配
  684. */
  685. urlMatch(reg, mode = 'SINGLE') {
  686. let result = false
  687. const href = location.href
  688. if (mode == 'SINGLE') {
  689. if (reg instanceof Array) {
  690. if (reg.length > 0) {
  691. reg = reg[0]
  692. } else {
  693. reg = null
  694. }
  695. }
  696. if (reg) {
  697. result = reg.test(href)
  698. }
  699. } else {
  700. if (!(reg instanceof Array)) {
  701. reg = [reg]
  702. }
  703. if (reg.length > 0) {
  704. if (mode == 'AND') {
  705. result = true
  706. for (const r of reg) {
  707. if (!r.test(href)) {
  708. result = false
  709. break
  710. }
  711. }
  712. } else if (mode == 'OR') {
  713. for (const r of reg) {
  714. if (r.test(href)) {
  715. result = true
  716. break
  717. }
  718. }
  719. }
  720. }
  721. }
  722. return result
  723. },
  724. }
  725. /**
  726. * 日志
  727. */
  728. this.logger = {
  729. /**
  730. * 打印格式化日志
  731. * @param {*} message 日志信息
  732. * @param {string} label 日志标签
  733. * @param {boolean} [error] 是否错误信息
  734. */
  735. log(message, label, error) {
  736. const output = console[error ? 'error' : 'log']
  737. const type = typeof message == 'string' ? '%s' : '%o'
  738. output(`%c${label}%c${type}`, logCss, '', message)
  739. },
  740.  
  741. /**
  742. * 打印日志
  743. * @param {*} message 日志信息
  744. */
  745. info(message) {
  746. if (message === undefined) {
  747. message = '[undefined]'
  748. } else if (message === null) {
  749. message = '[null]'
  750. } else if (message === '') {
  751. message = '[empty string]'
  752. }
  753. if (api.options.label) {
  754. this.log(message, api.options.label)
  755. } else {
  756. console.log(message)
  757. }
  758. },
  759.  
  760. /**
  761. * 打印错误日志
  762. * @param {*} message 错误日志信息
  763. */
  764. error(message) {
  765. if (message === undefined) {
  766. message = '[undefined]'
  767. } else if (message === null) {
  768. message = '[null]'
  769. } else if (message === '') {
  770. message = '[empty string]'
  771. }
  772. if (api.options.label) {
  773. this.log(message, api.options.label, true)
  774. } else {
  775. console.error(message)
  776. }
  777. },
  778. }
  779.  
  780. GM_addStyle(`
  781. :root {
  782. --light-text-color: white;
  783. --shadow-color: #000000bf;
  784. }
  785.  
  786. .${api.options.id}-msgbox {
  787. z-index: 65535;
  788. background-color: var(--shadow-color);
  789. font-size: 16px;
  790. max-width: 24em;
  791. min-width: 2em;
  792. color: var(--light-text-color);
  793. padding: 0.5em 1em;
  794. border-radius: 0.6em;
  795. opacity: 0;
  796. transition: opacity ${api.options.fadeTime}ms ease-in-out;
  797. user-select: none;
  798. }
  799.  
  800. .${api.options.id}-msgbox .gm-advanced-table td {
  801. vertical-align: middle;
  802. }
  803. .${api.options.id}-msgbox .gm-advanced-table td:first-child {
  804. padding-right: 0.6em;
  805. }
  806. `)
  807. }
  808. }