UserscriptAPI

My API for userscripts.

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

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/409641/849737/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 | {className: string}} 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 || typeof el.className == 'string') {
  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. return false
  223. },
  224. }
  225. /** 信息通知相关 */
  226. this.message = {
  227. /**
  228. * 创建信息
  229. * @param {string} msg 信息
  230. * @param {Object} [config] 设置
  231. * @param {boolean} [config.autoClose=true] 是否自动关闭信息,配合 `config.ms` 使用
  232. * @param {number} [config.ms=1500] 显示时间(单位:ms,不含渐显/渐隐时间)
  233. * @param {boolean} [config.html=false] 是否将 `msg` 理解为 HTML
  234. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  235. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,相当于设置为 `{ top: '70%', left: '50%' }`
  236. * @return {HTMLElement} 信息框元素
  237. */
  238. create(msg, config) {
  239. const defaultConfig = {
  240. autoClose: true,
  241. ms: 1500,
  242. html: false,
  243. width: null,
  244. position: {
  245. top: '70%',
  246. left: '50%',
  247. },
  248. }
  249. config = { ...defaultConfig, ...config }
  250.  
  251. const msgbox = document.body.appendChild(document.createElement('div'))
  252. msgbox.className = `${api.options.id}-msgbox`
  253. if (config.width) {
  254. msgbox.style.minWidth = 'auto' // 为什么一个是 auto 一个是 none?真是神奇的设计
  255. msgbox.style.maxWidth = 'none'
  256. msgbox.style.width = config.width
  257. }
  258.  
  259. msgbox.style.display = 'block'
  260. setTimeout(() => {
  261. api.dom.setAbsoluteCenter(msgbox, config.position)
  262. }, 10)
  263.  
  264. if (config.html) {
  265. msgbox.innerHTML = msg
  266. } else {
  267. msgbox.innerText = msg
  268. }
  269. api.dom.fade(true, msgbox, () => {
  270. if (config.autoClose) {
  271. setTimeout(() => {
  272. this.close(msgbox)
  273. }, config.ms)
  274. }
  275. })
  276. return msgbox
  277. },
  278.  
  279. /**
  280. * 关闭信息
  281. * @param {HTMLElement} msgbox 信息框元素
  282. */
  283. close(msgbox) {
  284. if (msgbox) {
  285. api.dom.fade(false, msgbox, () => {
  286. msgbox && msgbox.remove()
  287. })
  288. }
  289. },
  290.  
  291. /**
  292. * 创建高级信息
  293. * @param {HTMLElement} el 启动元素
  294. * @param {string} msg 信息
  295. * @param {string} flag 标志信息
  296. * @param {Object} [config] 设置
  297. * @param {string} [config.flagSize='1.8em'] 标志大小
  298. * @param {string} [config.width] 信息框的宽度,不设置的情况下根据内容决定,但有最小宽度和最大宽度的限制
  299. * @param {{top: string, left: string}} [config.position] 信息框的位置,不设置该项时,沿用 `API.message.create()` 的默认设置
  300. * @param {() => boolean} [config.disabled] 是否处于禁用状态
  301. */
  302. advanced(el, msg, flag, config) {
  303. const defaultConfig = {
  304. flagSize: '1.8em',
  305. // 不能把数据列出,否则解构的时候会出问题
  306. }
  307. config = { ...defaultConfig, ...config }
  308.  
  309. const _self = this
  310. el.show = false
  311. el.onmouseenter = function() {
  312. if (config.disabled && config.disabled()) {
  313. return
  314. }
  315.  
  316. const htmlMsg = `
  317. <table class="gm-advanced-table"><tr>
  318. <td style="font-size:${config.flagSize};line-height:${config.flagSize}">${flag}</td>
  319. <td>${msg}</td>
  320. </tr></table>
  321. `
  322. this.msgbox = _self.create(htmlMsg, { ...config, html: true, autoClose: false })
  323.  
  324. // 可能信息框刚好生成覆盖在 el 上,需要做一个处理
  325. this.msgbox.onmouseenter = function() {
  326. this.mouseOver = true
  327. }
  328. // 从信息框出来也会关闭信息框,防止覆盖的情况下无法关闭
  329. this.msgbox.onmouseleave = function() {
  330. _self.close(this)
  331. }
  332. }
  333. el.onmouseleave = function() {
  334. setTimeout(() => {
  335. if (this.msgbox && !this.msgbox.mouseOver) {
  336. this.msgbox.onmouseleave = null
  337. _self.close(this.msgbox)
  338. }
  339. })
  340. }
  341. },
  342. }
  343. /** 用于等待元素加载/条件达成再执行操作 */
  344. this.wait = {
  345. /**
  346. * 在条件满足后执行操作
  347. *
  348. * 当条件满足后,如果不存在终止条件,那么直接执行 `callback(result)`。
  349. *
  350. * 当条件满足后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否满足终止条件,称为终止条件的二次判断。
  351. * 如果在此期间,终止条件通过,则表示依然不满足条件,故执行 `onStop()` 而非 `callback(result)`。
  352. * 如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  353. *
  354. * @param {Object} options 选项
  355. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时满足条件
  356. * @param {(result) => void} [options.callback] 当满足条件时执行 `callback(result)`
  357. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  358. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  359. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  360. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  361. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  362. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  363. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  364. * @param {(e) => void} [options.onError] 条件检测过程中发生错误时执行 `onError()`
  365. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  366. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  367. * @returns {() => boolean} 执行后终止检测的函数
  368. */
  369. executeAfterConditionPassed(options) {
  370. const defaultOptions = {
  371. callback: result => api.logger.info(result),
  372. interval: api.options.waitInterval,
  373. timeout: api.options.waitTimeout,
  374. onTimeout: null,
  375. stopCondition: null,
  376. onStop: null,
  377. stopInterval: 50,
  378. stopTimeout: 0,
  379. stopOnError: false,
  380. timePadding: 0,
  381. }
  382. options = {
  383. ...defaultOptions,
  384. ...options,
  385. }
  386.  
  387. let tid
  388. let stop = false
  389. let cnt = 0
  390. let maxCnt
  391. if (options.timeout === 0) {
  392. maxCnt = 0
  393. } else {
  394. maxCnt = (options.timeout - options.timePadding) / options.interval
  395. }
  396. const task = async () => {
  397. let result = null
  398. try {
  399. result = await options.condition()
  400. } catch (e) {
  401. options.onError && options.onError.call(options, e)
  402. if (options.stopOnError) {
  403. clearInterval(tid)
  404. }
  405. }
  406. const stopResult = options.stopCondition && await options.stopCondition()
  407. if (stop) {
  408. clearInterval(tid)
  409. } else if (stopResult) {
  410. clearInterval(tid)
  411. options.onStop && options.onStop.call(options)
  412. } else if (maxCnt !== 0 && ++cnt > maxCnt) {
  413. clearInterval(tid)
  414. options.onTimeout && options.onTimeout.call(options)
  415. } else if (result) {
  416. clearInterval(tid)
  417. if (options.stopCondition && options.stopTimeout > 0) {
  418. this.executeAfterConditionPassed({
  419. condition: options.stopCondition,
  420. callback: options.onStop,
  421. interval: options.stopInterval,
  422. timeout: options.stopTimeout,
  423. onTimeout: () => options.callback.call(options, result)
  424. })
  425. } else {
  426. options.callback.call(options, result)
  427. }
  428. }
  429. }
  430. setTimeout(() => {
  431. tid = setInterval(task, options.interval)
  432. task()
  433. }, options.timePadding)
  434. return function() {
  435. stop = true
  436. }
  437. },
  438.  
  439. /**
  440. * 在元素加载完成后执行操作
  441. *
  442. * 当条件满足后,如果不存在终止条件,那么直接执行 `callback(element)`。
  443. *
  444. * 当条件满足后,如果存在终止条件,且 `stopTimeout` 大于 `0`,则还会在接下来的 `stopTimeout` 时间内判断是否满足终止条件,称为终止条件的二次判断。
  445. * 如果在此期间,终止条件通过,则表示依然不满足条件,故执行 `onStop()` 而非 `callback(element)`。
  446. * 如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(element)`。
  447. *
  448. * @param {Object} options 选项
  449. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  450. * @param {HTMLElement} [options.base=document] 基元素
  451. * @param {(element: HTMLElement) => void} [options.callback] 当 `element` 加载成功时执行 `callback(element)`
  452. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  453. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  454. * @param {() => void} [options.onTimeout] 检测超时时执行 `onTimeout()`
  455. * @param {string | (() => *)} [options.stopCondition] 终止条件。若为函数,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测;若为字符串,则作为元素选择器指定终止元素 `stopElement`,若该元素加载成功则终止检测
  456. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  457. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  458. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  459. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  460. * @returns {() => boolean} 执行后终止检测的函数
  461. */
  462. executeAfterElementLoaded(options) {
  463. const defaultOptions = {
  464. base: document,
  465. callback: el => api.logger.info(el),
  466. interval: 100,
  467. timeout: 5000,
  468. onTimeout: null,
  469. stopCondition: null,
  470. onStop: null,
  471. stopInterval: 50,
  472. stopTimeout: 0,
  473. timePadding: 0,
  474. }
  475. options = {
  476. ...defaultOptions,
  477. ...options,
  478. }
  479. return this.executeAfterConditionPassed({
  480. ...options,
  481. condition: () => options.base.querySelector(options.selector),
  482. stopCondition: () => {
  483. if (options.stopCondition) {
  484. if (options.stopCondition) {
  485. return options.stopCondition()
  486. } else if (typeof options.stopCondition == 'string') {
  487. return document.querySelector(options.stopCondition)
  488. }
  489. }
  490. },
  491. })
  492. },
  493.  
  494. /**
  495. * 等待条件满足
  496. *
  497. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  498. * @async
  499. * @see executeAfterConditionPassed
  500. * @param {Object} options 选项
  501. * @param {() => *} options.condition 条件,当 `condition()` 返回的 `result` 为真值时满足条件
  502. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  503. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  504. * @param {() => *} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  505. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  506. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  507. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  508. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  509. * @returns {Promise} `result`
  510. * @throws 当等待超时或者被终止时抛出
  511. */
  512. async waitForConditionPassed(options) {
  513. return new Promise((resolve, reject) => {
  514. this.executeAfterConditionPassed({
  515. ...options,
  516. callback: result => resolve(result),
  517. onTimeout: function() {
  518. reject(['TIMEOUT', 'waitForConditionPassed', this])
  519. },
  520. onStop: function() {
  521. reject(['STOP', 'waitForConditionPassed', this])
  522. },
  523. onError: function(e) {
  524. reject(['ERROR', 'waitForConditionPassed', this, e])
  525. },
  526. })
  527. })
  528. },
  529.  
  530. /**
  531. * 等待元素加载
  532. *
  533. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  534. * @async
  535. * @see executeAfterElementLoaded
  536. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  537. * @param {HTMLElement} [base=document] 基元素
  538. * @returns {Promise<HTMLElement>} `element`
  539. * @throws 当等待超时或者被终止时抛出
  540. */
  541. /**
  542. * 等待元素加载
  543. *
  544. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  545. * @async
  546. * @see executeAfterElementLoaded
  547. * @param {Object} options 选项
  548. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  549. * @param {HTMLElement} [options.base=document] 基元素
  550. * @param {number} [options.interval=API.waitInterval] 检测时间间隔(单位:ms)
  551. * @param {number} [options.timeout=API.waitTimeout] 检测超时时间,检测时间超过该值时终止检测(单位:ms);设置为 `0` 时永远不会超时
  552. * @param {string | (() => *)} [options.stopCondition] 终止条件。若为函数,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测;若为字符串,则作为元素选择器指定终止元素 `stopElement`,若该元素加载成功则终止检测
  553. * @param {number} [options.stopInterval=50] 终止条件二次判断期间的检测时间间隔(单位:ms)
  554. * @param {number} [options.stopTimeout=0] 终止条件二次判断期间的检测超时时间(单位:ms)
  555. * @param {number} [options.timePadding=0] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  556. * @returns {Promise<HTMLElement>} `element`
  557. * @throws 当等待超时或者被终止时抛出
  558. */
  559. async waitForElementLoaded() {
  560. let options
  561. if (arguments.length > 0) {
  562. if (typeof arguments[0] == 'string') {
  563. options = { selector: arguments[0] }
  564. if (arguments[1]) {
  565. options.base = arguments[1]
  566. }
  567. } else {
  568. options = arguments[0]
  569. }
  570. }
  571. return new Promise((resolve, reject) => {
  572. this.executeAfterElementLoaded({
  573. ...options,
  574. callback: element => resolve(element),
  575. onTimeout: function() {
  576. reject(['TIMEOUT', 'waitForElementLoaded', this])
  577. },
  578. onStop: function() {
  579. reject(['STOP', 'waitForElementLoaded', this])
  580. },
  581. })
  582. })
  583. },
  584. }
  585. /** 网络相关 */
  586. this.web = {
  587. /** @typedef {Object} GM_xmlhttpRequest_details */
  588. /** @typedef {Object} GM_xmlhttpRequest_response */
  589. /**
  590. * 发起网络请求
  591. * @async
  592. * @param {GM_xmlhttpRequest_details} details 定义及细节同 {@link GM_xmlhttpRequest} 的 `details`
  593. * @returns {Promise<GM_xmlhttpRequest_response>} 响应对象
  594. * @throws 当请求发生错误或者超时时抛出
  595. * @see {@link https://www.tampermonkey.net/documentation.php#GM_xmlhttpRequest GM_xmlhttpRequest}
  596. */
  597. async request(details) {
  598. if (details) {
  599. return new Promise((resolve, reject) => {
  600. const throwHandler = function(msg) {
  601. api.logger.error('NETWORK REQUEST ERROR')
  602. reject(msg)
  603. }
  604. details.onerror = details.onerror || (() => throwHandler(['ERROR', 'request', details]))
  605. details.ontimeout = details.ontimeout || (() => throwHandler(['TIMEOUT', 'request', details]))
  606. details.onload = details.onload || (response => resolve(response))
  607. GM_xmlhttpRequest(details)
  608. })
  609. }
  610. },
  611.  
  612. /**
  613. * 判断当前 URL 是否匹配
  614. * @param {RegExp} reg 用于判断是否匹配的正则表达式
  615. * @returns {boolean} 是否匹配
  616. */
  617. urlMatch(reg) {
  618. return reg.test(location.href)
  619. },
  620. }
  621. /**
  622. * 日志
  623. */
  624. this.logger = {
  625. /**
  626. * 打印格式化日志
  627. * @param {*} message 日志信息
  628. * @param {string} label 日志标签
  629. * @param {boolean} [error] 是否错误信息
  630. */
  631. log(message, label, error) {
  632. const css = `
  633. background-color: black;
  634. color: white;
  635. border-radius: 2px;
  636. padding: 2px;
  637. margin-right: 2px;
  638. `
  639. const output = console[error ? 'error' : 'log']
  640. const type = typeof message == 'string' ? '%s' : '%o'
  641. output(`%c${label}%c${type}`, css, '', message)
  642. },
  643.  
  644. /**
  645. * 打印日志
  646. * @param {*} message 日志信息
  647. */
  648. info(message) {
  649. if (message !== undefined) {
  650. if (api.options.label) {
  651. this.log(message, api.options.label)
  652. } else {
  653. console.log(message)
  654. }
  655. }
  656. },
  657.  
  658. /**
  659. * 打印错误日志
  660. * @param {*} message 错误日志信息
  661. */
  662. error(message) {
  663. if (message !== undefined) {
  664. if (api.options.label) {
  665. this.log(message, api.options.label, true)
  666. } else {
  667. console.error(message)
  668. }
  669. }
  670. },
  671. }
  672.  
  673. GM_addStyle(`
  674. :root {
  675. --light-text-color: white;
  676. --shadow-color: #000000bf;
  677. }
  678.  
  679. .${api.options.id}-msgbox {
  680. z-index: 65535;
  681. background-color: var(--shadow-color);
  682. font-size: 16px;
  683. max-width: 24em;
  684. min-width: 2em;
  685. color: var(--light-text-color);
  686. padding: 0.5em 1em;
  687. border-radius: 0.6em;
  688. opacity: 0;
  689. transition: opacity ${api.options.fadeTime}ms ease-in-out;
  690. user-select: none;
  691. }
  692.  
  693. .${api.options.id}-msgbox .gm-advanced-table td {
  694. vertical-align: middle;
  695. }
  696. .${api.options.id}-msgbox .gm-advanced-table td:first-child {
  697. padding-right: 0.6em;
  698. }
  699. `)
  700. }
  701. }