From 7bd278657b669eca6c6713368f180410e0143c5d Mon Sep 17 00:00:00 2001 From: blankie Date: Tue, 19 Sep 2023 21:02:01 +1000 Subject: [PATCH] Add Abort Network Requests on Escape --- Abort Network Requests on Escape.user.js | 71 ++++++++++++++++++++++++ README.md | 5 ++ 2 files changed, 76 insertions(+) create mode 100644 Abort Network Requests on Escape.user.js diff --git a/Abort Network Requests on Escape.user.js b/Abort Network Requests on Escape.user.js new file mode 100644 index 0000000..e2c2e8c --- /dev/null +++ b/Abort Network Requests on Escape.user.js @@ -0,0 +1,71 @@ +// ==UserScript== +// @name Abort Network Requests on Escape +// @namespace blankie-scripts +// @match http*://*/* +// @grant none +// @version 1.0.0 +// @author blankie +// @description Aborts network requests invoked from XMLHttpRequest and fetch() when Escape is pressed +// @run-at document-start +// @inject-into page +// ==/UserScript== + +"use strict"; + +let activeXHRs = new Set(); +let abortControllers = new Set(); + + +unsafeWindow.XMLHttpRequest = new Proxy(unsafeWindow.XMLHttpRequest, { + construct: function(target, args) { + let xhr = new target(...args); + xhr.addEventListener("loadstart", function() { + activeXHRs.add(this); + }, {passive: true}); + xhr.addEventListener("loadend", function() { + activeXHRs.delete(this); + }, {passive: true}); + return xhr; + } +}); + +let originalFetch = unsafeWindow.fetch; +unsafeWindow.fetch = function(resource, options = undefined) { + let abortController = new AbortController(); + options = options || {}; + + let originalSignal = options.signal; + if (originalSignal) { + originalSignal.addEventListener("abort", function() { + abortController.abort(originalSignal.reason); + }, {passive: true}); + } + options.signal = abortController.signal; + + abortControllers.add(abortController); + + return originalFetch.call(this, resource, options).finally(function() { + abortControllers.delete(abortController); + }); +} + + +function abortAllRequests() { + for (let activeXHR of activeXHRs) { + activeXHR.abort(); + } + activeXHRs.clear(); + + let error = new DOMException("Network request cancelled by Abort Network Requests on Escape", "NetworkError"); + for (let abortController of abortControllers) { + abortController.abort(error); + } + abortControllers.clear(); +} + +window.addEventListener("keydown", function(event) { + if (event.key !== "Escape" || event.target !== document.body || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } + abortAllRequests(); +}, {passive: true}); \ No newline at end of file diff --git a/README.md b/README.md index 78c0030..15bc555 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,11 @@ User scripts I made to deal with some itches +## Abort Network Requests on Escape + +A userscript that automatically cancels network requests initiated by +Javascript when Escape is pressed + ## Anti-Thot Hacky script to get rid of thot notifications