http-on-pages

Initiate an XHR request on the page

当前为 2024-05-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name http-on-pages
  3. // @namespace https://github.com/pansong291/
  4. // @version 0.1.9
  5. // @description Initiate an XHR request on the page
  6. // @description:zh 在页面上发起 XHR 请求
  7. // @author paso
  8. // @license Apache-2.0
  9. // @match *://*/*
  10. // @icon data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%201024%201024%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M474.937%20387.054c0-20.275%2016.638-36.403%2036.913-36.403h53.035L362.632%20148.402%20160.377%20350.65h53.297c20.275%200%2036.652%2016.128%2036.652%2036.403v259.959c0%2020.276-16.377%2036.914-36.652%2036.914-20.021%200-36.919-16.638-36.919-36.914V423.967H71.732c-20.015%200-36.137-17.159-36.137-36.914%200-9.883%203.644-19.244%2010.138-25.999l291.42-291.16c13.781-13.521%2037.435-13.521%2051.217%200l291.421%20291.161c13.776%2014.552%2013.776%2037.956%200%2051.987-7.282%206.766-16.898%2010.925-25.999%2010.925H548.247v223.045c0%2020.276-16.377%2036.914-36.398%2036.914h-53.291l202.509%20202.26%20201.994-202.26H809.77c-20.276%200-36.398-16.638-36.398-36.914V387.054c0-20.275%2016.122-36.403%2036.398-36.403s36.914%2016.128%2036.914%2036.403v223.567h104.768c9.617%200%2018.717%203.116%2026.254%2010.393a37.359%2037.359%200%200%201%200%2051.999L687.328%20962.609l-0.261%201.043c-14.558%2014.563-37.957%2014.563-51.993%200l-291.16-290.639c-6.239-6.755-10.659-16.117-10.659-26%200-20.275%2016.898-36.392%2036.397-36.392h105.285V387.054z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E
  11. // @grant none
  12. // @noframes
  13. // @run-at context-menu
  14. // @require https://update.greasyfork.org/scripts/473443/1374764/popup-inject.js
  15. // ==/UserScript==
  16.  
  17. /**
  18. * @typedef {object} ReqObj
  19. * @property {string} method
  20. * @property {string} url
  21. * @property {string} code
  22. * @property {number} timestamp
  23. */
  24. /**
  25. * @typedef {object} ProxiedReqExtension
  26. * @property {(i: number, v: ReqObj) => void} insert
  27. * @property {(i: number) => ReqObj} remove
  28. * @property {ReqObj} selected
  29. */
  30. /**
  31. * @typedef {ReqObj[] & ProxiedReqExtension} ProxiedReqArray
  32. */
  33. ;(function () {
  34. 'use strict'
  35. const namespace = 'paso-http-on-pages'
  36. const injectHint = 'const data = { headers: {}, params: {}, body: void 0, withCredentials: true }'
  37. const injectHtml = `
  38. <div class="tip-box info">${injectHint}</div>
  39. <div class="flex gap-4">
  40. <select id="ipt-req-sel" class="input"></select>
  41. <button id="btn-req-rem" type="button" class="button square">
  42. <svg width="16" height="16" fill="currentcolor">
  43. <path d="M2 7h12v2H2Z"></path>
  44. </svg>
  45. </button>
  46. <button id="btn-req-add" type="button" class="button square">
  47. <svg width="16" height="16" fill="currentcolor">
  48. <path d="M2 7H7V2H9V7H14V9H9V14H7V9H2Z"></path>
  49. </svg>
  50. </button>
  51. </div>
  52. <div class="flex gap-4">
  53. <select id="ipt-method" class="input"></select>
  54. <input type="text" id="ipt-url" class="input" autocomplete="off">
  55. <button type="button" id="btn-submit" class="button">Submit</button>
  56. </div>
  57. <textarea id="ipt-code" class="input" spellcheck="false"></textarea>
  58. <div id="error-tip-box"></div>`
  59. const injectStyle = `
  60. <style>
  61. .popup {
  62. gap: 4px;
  63. }
  64. .gap-4 {
  65. gap: 4px;
  66. }
  67. .tip-box.info {
  68. background: #d3dff7;
  69. border-left: 6px solid #3d7fff;
  70. border-radius: 4px;
  71. padding: 16px;
  72. }
  73. .button.square {
  74. width: 32px;
  75. padding: 0;
  76. }
  77. #ipt-method {
  78. width: 90px;
  79. }
  80. #ipt-url {
  81. flex: 1 0 300px;
  82. }
  83. #btn-submit {
  84. width: 100px;
  85. }
  86. #ipt-code {
  87. height: 400px;
  88. }
  89. #error-tip-box {
  90. background: #fdd;
  91. border-left: 6px solid #f66;
  92. border-radius: 4px;
  93. padding: 16px;
  94. }
  95. #error-tip-box:empty {
  96. display: none;
  97. }
  98. </style>`
  99. window.paso.injectPopup({
  100. namespace,
  101. actionName: 'Http Request',
  102. collapse: '70%',
  103. content: injectHtml,
  104. style: injectStyle
  105. }).then((result) => {
  106. const { popup } = result.elem
  107. const { createElement } = result.func
  108. popup.classList.add('monospace')
  109. const element = {
  110. ipt_req_sel: popup.querySelector('#ipt-req-sel'),
  111. btn_req_rem: popup.querySelector('#btn-req-rem'),
  112. btn_req_add: popup.querySelector('#btn-req-add'),
  113. ipt_method: popup.querySelector('#ipt-method'),
  114. ipt_url: popup.querySelector('#ipt-url'),
  115. ipt_code: popup.querySelector('#ipt-code'),
  116. btn_submit: popup.querySelector('#btn-submit'),
  117. error_tip: popup.querySelector('#error-tip-box')
  118. }
  119. const method_options = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH']
  120. element.ipt_method.innerHTML = method_options.map(op => `<option value="${op}">${op}</option>`).join('')
  121. /**
  122. * @type {ProxiedReqArray}
  123. */
  124. const reactiveRequests = new Proxy([], {
  125. get(target, prop, receiver) {
  126. if (prop === 'insert') {
  127. return (index, value) => {
  128. checkIndex(index, target.length + 1)
  129. const opt = createElement('option', { value: value.timestamp }, [formatDate(value.timestamp)])
  130. if (target.length === 0 || index === target.length)
  131. element.ipt_req_sel.append(opt)
  132. else
  133. element.ipt_req_sel.children[index].before(opt)
  134. target.splice(index, 0, value)
  135. }
  136. } else if (prop === 'remove') {
  137. return (index) => {
  138. checkIndex(index, target.length)
  139. if (receiver.selected === target[index])
  140. receiver.selected = target[index > 0 ? index - 1 : 1]
  141. element.ipt_req_sel.children[index].remove()
  142. return target.splice(index, 1)[0]
  143. }
  144. } else if (prop === 'push') {
  145. return (value) => receiver.insert(target.length, value)
  146. } else if (prop === 'selected') {
  147. if (!target.selected) {
  148. const v = String(element.ipt_req_sel.value)
  149. target.selected = target.find((r) => String(r.timestamp) === v)
  150. }
  151. }
  152. return target[prop]
  153. },
  154. set(target, prop, newValue, receiver) {
  155. if (prop === 'selected') {
  156. target.selected = newValue
  157. element.ipt_req_sel.value = newValue?.timestamp || ''
  158. element.ipt_method.value = newValue?.method || ''
  159. element.ipt_url.value = newValue?.url || ''
  160. element.ipt_code.value = newValue?.code || ''
  161. }
  162. return true
  163. }
  164. })
  165. /**
  166. * @param {string|number} ts
  167. * @returns {ReqObj}
  168. */
  169. const getReqByTimestamp = (ts) => {
  170. ts = String(ts)
  171. return reactiveRequests.find((r) => String(r.timestamp) === ts)
  172. }
  173.  
  174. const cache = getCache()
  175. if (cache?.requests && Array.isArray(cache.requests)) {
  176. for (const req of cache.requests) {
  177. reactiveRequests.push(createRequestObj(req))
  178. }
  179. }
  180. if (!reactiveRequests.length) reactiveRequests.push(createRequestObj())
  181. reactiveRequests.selected = getReqByTimestamp(cache?.selected) || reactiveRequests[0]
  182.  
  183. element.ipt_req_sel.addEventListener('change', (e) => reactiveRequests.selected = getReqByTimestamp(e.currentTarget.value))
  184. element.btn_req_rem.addEventListener('click', () => {
  185. if (reactiveRequests.length <= 1) return
  186. reactiveRequests.remove(reactiveRequests.indexOf(reactiveRequests.selected))
  187. })
  188. element.btn_req_add.addEventListener('click', () => {
  189. const obj = createRequestObj()
  190. reactiveRequests.push(obj)
  191. reactiveRequests.selected = obj
  192. })
  193. element.ipt_method.addEventListener('change', (e) => reactiveRequests.selected.method = e.currentTarget.value)
  194. element.ipt_url.addEventListener('change', (e) => reactiveRequests.selected.url = e.currentTarget.value)
  195. element.ipt_code.addEventListener('change', (e) => reactiveRequests.selected.code = e.currentTarget.value)
  196. element.btn_submit.addEventListener('click', tryTo(() => {
  197. const selReq = reactiveRequests.selected
  198. if (!selReq.url) throw 'Url is required'
  199. const isGet = selReq.method === 'GET'
  200. const data = {
  201. headers: { 'Content-Type': isGet ? 'application/x-www-form-urlencoded' : 'application/json' },
  202. params: {},
  203. body: void 0,
  204. withCredentials: true
  205. }
  206. const handleData = new Function('data', selReq.code)
  207. handleData.call(data, data)
  208. const xhr = new XMLHttpRequest()
  209. xhr.open(selReq.method, selReq.url + serializeQueryParam(data.params))
  210. xhr.withCredentials = !!data.withCredentials
  211. Object.entries(data.headers).forEach(([n, v]) => xhr.setRequestHeader(n, v))
  212. xhr.send(isGet ? void 0 : jsonSerialize(data.body))
  213. saveCache({ requests: reactiveRequests, selected: selReq.timestamp })
  214. element.error_tip.innerText = ''
  215. }, e => element.error_tip.innerText = String(e)))
  216. })
  217.  
  218. /**
  219. * @param {function} fn
  220. * @param {function} [errorCallback]
  221. * @returns {function}
  222. */
  223. function tryTo(fn, errorCallback) {
  224. return function (...args) {
  225. try {
  226. fn.apply(this, args)
  227. } catch (e) {
  228. console.error(e)
  229. errorCallback?.(e)
  230. }
  231. }
  232. }
  233.  
  234. /**
  235. * @param {string | Record<string, string>} [param]
  236. * @param {string} [prefix='?']
  237. * @returns {string}
  238. */
  239. function serializeQueryParam(param, prefix = '?') {
  240. if (!param) return ''
  241. if (typeof param === 'string') return prefix + param
  242. const str = Object.entries(flatten(param)).flatMap(([k, v]) => {
  243. if (v === null || v === void 0) return []
  244. return [k + '=' + encodeURIComponent(String(v))]
  245. }).join('&')
  246. if (str) return prefix + str
  247. return str
  248. }
  249.  
  250. /**
  251. * @param {*} obj
  252. * @param {string} [name='']
  253. * @returns {Record<string, *>}
  254. */
  255. function flatten(obj, name = '') {
  256. const result = {}
  257. if (!obj || typeof obj !== 'object') {
  258. if (!name) return [obj]
  259. result[name] = obj
  260. } else {
  261. const isArr = Array.isArray(obj)
  262. Object.entries(obj).forEach(([k, v]) => {
  263. Object.entries(flatten(v, !name ? k : isArr ? `${name}[${k}]` : `${name}.${k}`)).forEach(([k2, v2]) => {
  264. result[k2] = v2
  265. })
  266. })
  267. }
  268. return result
  269. }
  270.  
  271. /**
  272. * @param {?ReqObj} [base]
  273. * @returns {ReqObj}
  274. */
  275. function createRequestObj(base) {
  276. return {
  277. method: base?.method || 'GET',
  278. url: base?.url || '',
  279. code: base?.code || '',
  280. timestamp: base?.timestamp || Date.now()
  281. }
  282. }
  283.  
  284. /**
  285. * @param {number} index
  286. * @param {number} length
  287. */
  288. function checkIndex(index, length) {
  289. if (index < 0 || index >= length) throw new RangeError(`Index out of bounds error.\nindex: ${index}\nlength: ${length}`)
  290. }
  291.  
  292. /**
  293. * @param {*} [date]
  294. * @returns {string}
  295. */
  296. function formatDate(date) {
  297. date = new Date(date || null)
  298. const year = formatNumber(date.getFullYear(), 4)
  299. const month = formatNumber(date.getMonth())
  300. const day = formatNumber(date.getDate())
  301. const hour = formatNumber(date.getHours())
  302. const minute = formatNumber(date.getMinutes())
  303. const second = formatNumber(date.getSeconds())
  304. const mill = formatNumber(date.getMilliseconds(), 3)
  305. return `${year}-${month}-${day} ${hour}:${minute}:${second}.${mill}`
  306. }
  307.  
  308. /**
  309. * @param {number} num
  310. * @param {number} [count=2]
  311. * @returns {string}
  312. */
  313. function formatNumber(num, count = 2) {
  314. return String(num).padStart(count, '0')
  315. }
  316.  
  317. /**
  318. * @param {*} obj
  319. * @returns {string}
  320. */
  321. function jsonSerialize(obj) {
  322. if (typeof obj === 'string') return obj
  323. return JSON.stringify(obj)
  324. }
  325.  
  326. /**
  327. * @param {*} obj
  328. */
  329. function saveCache(obj) {
  330. localStorage.setItem(namespace, JSON.stringify(obj))
  331. }
  332.  
  333. /**
  334. * @returns {{requests: ReqObj[], selected: string} | undefined}
  335. */
  336. function getCache() {
  337. const str = localStorage.getItem(namespace)
  338. try {
  339. if (str) return JSON.parse(str)
  340. } catch (e) {
  341. console.error(e)
  342. }
  343. }
  344. })()