CORS-via-GM

CORS via Greasemonkey/Tampermonkey

当前为 2022-03-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name CORS-via-GM
  3. // @description CORS via Greasemonkey/Tampermonkey
  4. // @version 1.0
  5. // @include /^(file:///.*/index.html|https?://(127.0.0.1|192.168.\d+.\d+|localhost)(:\d+)?/((([^/]*/)?bundled/)?index.html)?)(\?.*|$)/
  6. // @include /\b(pages\.dev|onrender\.com)\b/
  7. // @connect *
  8. // @grant GM_xmlhttpRequest
  9. // @namespace https://greasyfork.org/users/882700
  10. // @license WTFPL
  11. // ==/UserScript==
  12.  
  13.  
  14. const CORSViaGM = document.body.appendChild(Object.assign(document.createElement('div'), { id: 'CORSViaGM' }))
  15.  
  16. addEventListener('fetchViaGM', e => GM_fetch(e.detail.forwardingFetch))
  17.  
  18. CORSViaGM.init = function (window) {
  19. if (!window) throw 'The `window` parameter must be passed in!'
  20. window.fetch = window.fetchViaGM = fetchViaGM.bind(window)
  21.  
  22. // Support for service worker
  23. window.forwardingFetch = new BroadcastChannel('forwardingFetch')
  24. window.forwardingFetch.onmessage = async e => {
  25. const req = e.data
  26. const { url } = req
  27. const res = await fetchViaGM(url, req)
  28. const response = await res.blob()
  29. window.forwardingFetch.postMessage({ type: 'fetchResponse', url, response })
  30. }
  31.  
  32. window._CORSViaGM && window._CORSViaGM.inited.done()
  33.  
  34. const info = '🙉 CORS-via-GM initiated!'
  35. console.info(info)
  36. return info
  37. }
  38.  
  39.  
  40. function GM_fetch(p) {
  41. GM_xmlhttpRequest({
  42. ...p.init,
  43. url: p.url, method: p.init.method || 'GET',
  44. onload: responseDetails => p.res(new Response(responseDetails.response, responseDetails))
  45. })
  46. }
  47.  
  48. function fetchViaGM(url, init) {
  49. let _r
  50. const p = new Promise(r => _r = r)
  51. p.res = _r
  52. p.url = url
  53. p.init = init || {}
  54. dispatchEvent(new CustomEvent('fetchViaGM', { detail: { forwardingFetch: p } }))
  55. return p
  56. }