UserscriptAPI

My API for userscripts.

As of 2021-09-27. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/409641/974252/UserscriptAPI.js

  1. /* exported UserscriptAPI */
  2. /**
  3. * UserscriptAPI
  4. *
  5. * 需要引入模块方可工作,详见 `README.md`。
  6. * @version 2.2.0.20210925
  7. * @author Laster2800
  8. * @see {@link https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI UserscriptAPI}
  9. */
  10. class UserscriptAPI {
  11. /** @type {{[name: string]: Function}} 可访问模块 */
  12. static #modules = {}
  13. /** @type {string[]} 待添加模块样式队列 */
  14. #moduleCssQueue = []
  15.  
  16. /**
  17. * @param {Object} [options] 选项
  18. * @param {string} [options.id='default'] 标识符
  19. * @param {string} [options.label] 日志标签,为空时不设置标签
  20. * @param {Object} [options.wait] `wait` API 默认选项(默认值见构造器代码)
  21. * @param {Object} [options.wait.condition] `wait` 条件 API 默认选项
  22. * @param {Object} [options.wait.element] `wait` 元素 API 默认选项
  23. * @param {number} [options.fadeTime=400] UI 渐变时间
  24. */
  25. constructor(options) {
  26. this.options = {
  27. id: 'default',
  28. label: null,
  29. fadeTime: 400,
  30. ...options,
  31. wait: {
  32. condition: {
  33. callback: result => this.logger.info(result),
  34. interval: 100,
  35. timeout: 10000,
  36. onTimeout: options => this.logger[options.stopOnTimeout ? 'error' : 'warn']('executeAfterConditionPassed: TIMEOUT', options),
  37. stopOnTimeout: true,
  38. stopCondition: null,
  39. onStop: options => this.logger.error('executeAfterConditionPassed: STOP', options),
  40. stopInterval: 50,
  41. stopTimeout: 0,
  42. onError: (options, e) => this.logger.error('executeAfterConditionPassed: ERROR', options, e),
  43. stopOnError: true,
  44. timePadding: 0,
  45. ...options?.wait?.condition,
  46. },
  47. element: {
  48. base: document,
  49. exclude: null,
  50. callback: el => this.logger.info(el),
  51. subtree: true,
  52. multiple: false,
  53. repeat: false,
  54. throttleWait: 100,
  55. timeout: 10000,
  56. onTimeout: options => this.logger[options.stopOnTimeout ? 'error' : 'warn']('executeAfterElementLoaded: TIMEOUT', options),
  57. stopOnTimeout: false,
  58. stopCondition: null,
  59. onStop: options => this.logger.error('executeAfterElementLoaded: STOP', options),
  60. onError: (options, e) => this.logger.error('executeAfterElementLoaded: ERROR', options, e),
  61. stopOnError: true,
  62. timePadding: 0,
  63. ...options?.wait?.element,
  64. },
  65. },
  66. }
  67.  
  68. /** @type {UserscriptAPIDom} */
  69. this.dom = this.#getModuleInstance('dom')
  70. /** @type {UserscriptAPIMessage} */
  71. this.message = this.#getModuleInstance('message')
  72. /** @type {UserscriptAPIWait} */
  73. this.wait = this.#getModuleInstance('wait')
  74. /** @type {UserscriptAPIWeb} */
  75. this.web = this.#getModuleInstance('web')
  76.  
  77. if (!this.message) {
  78. this.message = {
  79. api: this,
  80. alert: this.base.alert,
  81. confirm: this.base.confirm,
  82. prompt: this.base.prompt,
  83. }
  84. }
  85.  
  86. for (const css of this.#moduleCssQueue) {
  87. this.base.addStyle(css)
  88. }
  89. }
  90.  
  91. /**
  92. * 注册模块
  93. * @param {string} name 模块名称
  94. * @param {Object} module 模块类
  95. */
  96. static registerModule(name, module) {
  97. this.#modules[name] = module
  98. }
  99. /**
  100. * 获取模块实例
  101. * @param {string} name 模块名称
  102. * @returns {Object} 模块实例,无对应模块时返回 `null`
  103. */
  104. #getModuleInstance(name) {
  105. const module = UserscriptAPI.#modules[name]
  106. return module ? new module(this) : null
  107. }
  108.  
  109. /**
  110. * 初始化模块样式(仅应在模块构造器中使用)
  111. * @param {string} css 样式
  112. */
  113. initModuleStyle(css) {
  114. this.#moduleCssQueue.push(css)
  115. }
  116.  
  117. /**
  118. * UserscriptAPIBase
  119. * @version 1.2.0.20210927
  120. */
  121. base = new class UserscriptAPIBase {
  122. /**
  123. * @param {UserscriptAPI} api `UserscriptAPI`
  124. */
  125. constructor(api) {
  126. this.api = api
  127. }
  128.  
  129. /**
  130. * 添加样式
  131. * @param {string} css 样式
  132. * @param {Document} [doc=document] 文档
  133. * @returns {HTMLStyleElement} `<style>`
  134. */
  135. addStyle(css, doc = document) {
  136. const { api } = this
  137. const style = doc.createElement('style')
  138. style.className = `${api.options.id}-style`
  139. style.textContent = css
  140. const parent = doc.head || doc.documentElement
  141. if (parent) {
  142. parent.append(style)
  143. } else { // 极端情况下会出现,DevTools 网络+CPU 双限制可模拟
  144. api.wait?.waitForConditionPassed({
  145. condition: () => doc.head || doc.documentElement,
  146. timeout: 0,
  147. }).then(parent => parent.append(style))
  148. }
  149. return style
  150. }
  151.  
  152. /**
  153. * 判断给定 URL 是否匹配
  154. * @param {RegExp | RegExp[]} regex 用于判断是否匹配的正则表达式,或正则表达式数组
  155. * @param {'OR' | 'AND'} [mode='OR'] 匹配模式
  156. * @returns {boolean} 是否匹配
  157. */
  158. urlMatch(regex, mode = 'OR') {
  159. let result = false
  160. const { href } = location
  161. if (Array.isArray(regex)) {
  162. if (regex.length > 0) {
  163. if (mode === 'AND') {
  164. result = true
  165. for (const ex of regex) {
  166. if (!ex.test(href)) {
  167. result = false
  168. break
  169. }
  170. }
  171. } else if (mode === 'OR') {
  172. for (const ex of regex) {
  173. if (ex.test(href)) {
  174. result = true
  175. break
  176. }
  177. }
  178. }
  179. }
  180. } else {
  181. result = regex.test(href)
  182. }
  183. return result
  184. }
  185.  
  186. /**
  187. * 初始化 `urlchange` 事件
  188. * @example
  189. * window.addEventListener('urlchange', e => { ... })
  190. * window.addEventListener('urlchange', e => e.stopPropagation(), true)
  191. * window.onurlchange = function(e) { ... }
  192. * @see {@link https://stackoverflow.com/a/52809105 How to detect if URL has changed after hash in JavaScript}
  193. * @see {@link https://stackoverflow.com/a/69342637 Event bubbles before captured on `window`}
  194. */
  195. initUrlchangeEvent() {
  196. if (unsafeWindow[Symbol.for('onurlchange')] === undefined) {
  197. let url = new URL(location.href)
  198. const dispatchEvent = () => {
  199. const event = new CustomEvent('urlchange', {
  200. detail: { prev: url, curr: new URL(location.href) },
  201. bubbles: true,
  202. })
  203. url = event.detail.curr
  204. if (typeof window.onurlchange === 'function') { // 若直接调用则 eventPhase 不对,且会有一些其他问题
  205. // 这一方案只能让事件处理器属性在最后被激活,但正确的顺序是:https://stackoverflow.com/a/49806959
  206. // 要实现正确的顺序,需用 defineProperty 定义 onurlchange,但 Tampermonkey 已经定义了该属性
  207. // 尽管目前 Tampermonkey 定义的属性是可写的,但为了向前兼容性及简化代码考虑,决定采用当前方案
  208. window.addEventListener('urlchange', window.onurlchange, { once: true })
  209. }
  210. document.dispatchEvent(event) // 在 window 上 dispatch 不能确保在冒泡前捕获,至少目前是这样
  211. }
  212.  
  213. history.pushState = (f => (...args) => {
  214. const ret = Reflect.apply(f, history, args)
  215. dispatchEvent()
  216. return ret
  217. })(history.pushState)
  218. history.replaceState = (f => (...args) => {
  219. const ret = Reflect.apply(f, history, args)
  220. dispatchEvent()
  221. return ret
  222. })(history.replaceState)
  223. window.addEventListener('popstate', () => {
  224. dispatchEvent()
  225. })
  226. unsafeWindow[Symbol.for('onurlchange')] = true
  227. }
  228. }
  229.  
  230. /**
  231. * 生成消抖函数
  232. * @param {Function} fn 目标函数
  233. * @param {number} [wait=0] 消抖延迟
  234. * @param {Object} [options] 选项
  235. * @param {boolean} [options.leading] 是否在延迟开始前调用目标函数
  236. * @param {boolean} [options.trailing=true] 是否在延迟结束后调用目标函数
  237. * @param {number} [options.maxWait=0] 最大延迟时间(非准确),`0` 表示禁用
  238. * @returns {Function} 消抖函数 `debounced`,可调用 `debounced.cancel()` 取消执行
  239. */
  240. debounce(fn, wait = 0, options = {}) {
  241. options = {
  242. leading: false,
  243. trailing: true,
  244. maxWait: 0,
  245. ...options,
  246. }
  247.  
  248. let tid = null
  249. let start = null
  250. let execute = null
  251. let callback = null
  252.  
  253. /** @this {*} thisArg */
  254. function debounced(...args) {
  255. execute = () => {
  256. Reflect.apply(fn, this, args)
  257. execute = null
  258. }
  259. callback = () => {
  260. if (options.trailing) {
  261. execute?.()
  262. }
  263. tid = null
  264. start = null
  265. }
  266.  
  267. if (tid) {
  268. clearTimeout(tid)
  269. if (options.maxWait > 0 && Date.now() - start > options.maxWait) {
  270. callback()
  271. }
  272. }
  273.  
  274. if (!tid && options.leading) {
  275. execute?.()
  276. }
  277.  
  278. if (!start) {
  279. start = Date.now()
  280. }
  281.  
  282. tid = setTimeout(callback, wait)
  283. }
  284.  
  285. debounced.cancel = function() {
  286. if (tid) {
  287. clearTimeout(tid)
  288. tid = null
  289. start = null
  290. }
  291. }
  292.  
  293. return debounced
  294. }
  295.  
  296. /**
  297. * 生成节流函数
  298. * @param {Function} fn 目标函数
  299. * @param {number} [wait=0] 节流延迟(非准确)
  300. * @returns {Function} 节流函数 `throttled`,可调用 `throttled.cancel()` 取消执行
  301. */
  302. throttle(fn, wait = 0) {
  303. return this.debounce(fn, wait, {
  304. leading: true,
  305. trailing: true,
  306. maxWait: wait,
  307. })
  308. }
  309.  
  310. /**
  311. * 创建基础提醒对话框(异步)
  312. *
  313. * 若没有引入 `message` 模块,可使用 `api.message.alert()` 引用该方法。
  314. * @param {string} msg 信息
  315. */
  316. alert(msg) {
  317. const { label } = this.api.options
  318. return new Promise(resolve => {
  319. resolve(alert(`${label ? `${label}\n\n` : ''}${msg}`))
  320. })
  321. }
  322.  
  323. /**
  324. * 创建基础确认对话框(异步)
  325. *
  326. * 若没有引入 `message` 模块,可使用 `api.message.confirm()` 引用该方法。
  327. * @param {string} msg 信息
  328. * @returns {Promise<boolean>} 用户输入
  329. */
  330. confirm(msg) {
  331. const { label } = this.api.options
  332. return new Promise(resolve => {
  333. resolve(confirm(`${label ? `${label}\n\n` : ''}${msg}`))
  334. })
  335. }
  336.  
  337. /**
  338. * 创建基础输入对话框(异步)
  339. *
  340. * 若没有引入 `message` 模块,可使用 `api.message.prompt()` 引用该方法。
  341. * @param {string} msg 信息
  342. * @param {string} [val] 默认值
  343. * @returns {Promise<string>} 用户输入
  344. */
  345. prompt(msg, val) {
  346. const { label } = this.api.options
  347. return new Promise(resolve => {
  348. resolve(prompt(`${label ? `${label}\n\n` : ''}${msg}`, val))
  349. })
  350. }
  351. }(this)
  352.  
  353. /**
  354. * UserscriptAPILogger
  355. * @version 1.2.0.20210925
  356. */
  357. logger = new class UserscriptAPILogger {
  358. #logCss = `
  359. background-color: black;
  360. color: white;
  361. border-radius: 2px;
  362. padding: 2px;
  363. margin-right: 4px;
  364. `
  365.  
  366. /**
  367. * @param {UserscriptAPI} api `UserscriptAPI`
  368. */
  369. constructor(api) {
  370. this.api = api
  371. }
  372.  
  373. /**
  374. * 打印格式化日志
  375. * @param {'info' | 'warn' | 'error'} fn 日志函数名
  376. * @param {*[]} message 日志信息
  377. */
  378. #log(fn, ...message) {
  379. const output = console[fn]
  380. const label = this.api.options.label ?? ''
  381. const causes = []
  382. let template = null
  383. if (message.length > 0) {
  384. const types = []
  385. for (const [idx, m] of message.entries()) {
  386. if (m) {
  387. types.push(typeof m === 'string' ? '%s' : '%o')
  388. if (m instanceof Error && m.cause !== undefined) {
  389. causes.push(m.cause)
  390. }
  391. } else {
  392. if (m === undefined) {
  393. message[idx] = '[undefined]'
  394. } else if (m === null) {
  395. message[idx] = '[null]'
  396. } else if (m === '') {
  397. message[idx] = '[empty string]'
  398. }
  399. types.push(typeof message[idx] === 'string' ? '%s' : '%o')
  400. }
  401. }
  402. template = types.join(', ')
  403. } else {
  404. template = '[undefined]'
  405. }
  406. output(`%c${label}%c${template}`, this.#logCss, null, ...message)
  407. for (const [idx, cause] of causes.entries()) {
  408. output(`%c${label}%c${idx + 1}-th error is caused by %o`, this.#logCss, null, cause)
  409. }
  410. }
  411.  
  412. /**
  413. * 打印日志
  414. * @param {*[]} message 日志信息
  415. */
  416. info(...message) {
  417. this.#log('info', ...message)
  418. }
  419.  
  420. /**
  421. * 打印警告日志
  422. * @param {*[]} message 警告日志信息
  423. */
  424. warn(...message) {
  425. this.#log('warn', ...message)
  426. }
  427.  
  428. /**
  429. * 打印错误日志
  430. * @param {*[]} message 错误日志信息
  431. */
  432. error(...message) {
  433. this.#log('error', ...message)
  434. }
  435. }(this)
  436. }