UserscriptAPI

My API for userscripts.

目前為 2020-09-10 提交的版本,檢視 最新版本

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