UserscriptAPI

My API for userscripts.

当前为 2020-08-22 提交的版本,查看 最新版本

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