Created
June 2, 2023 17:08
-
-
Save Sv443/b2768fdebc8a037fbde4f4df9f7443a2 to your computer and use it in GitHub Desktop.
Simple userscript that can allow you to toggle any event on the window object on or off
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name window event toggler | |
// @namespace https://gist.github.com/Sv443/b2768fdebc8a037fbde4f4df9f7443a2 | |
// @match https://* | |
// @grant none | |
// @version 1.0 | |
// @author Sv443 | |
// @license WTFPL | |
// @run-at document-start | |
// @connect self | |
// ==/UserScript== | |
// which events you want to be able to toggle | |
const eventWhitelist = ["beforeunload"]; | |
const listeners = []; | |
let eventsEnabled = true; | |
function disableEvents() { | |
console.log("--- DISABLED EVENTS"); | |
eventsEnabled = false; | |
} | |
function enableEvents() { | |
console.log("--- ENABLED EVENTS"); | |
eventsEnabled = true; | |
} | |
// toggles every 10 seconds for testing | |
setTimeout(disableEvents, 10_000); | |
setTimeout(enableEvents, 20_000); | |
setTimeout(disableEvents, 30_000); | |
setTimeout(enableEvents, 40_000); | |
// based on https://gist.github.com/alessioalex/fc536ef87713d0a9ed89 | |
(function() { | |
Error.stackTraceLimit = Infinity; | |
(function(original) { | |
window.__proto__.addEventListener = function(type, listener, useCapture) { | |
if(eventWhitelist.includes(type)){ | |
listeners.push(listener); | |
console.log('------> addEventListener ' + type, listener, useCapture); | |
return original.apply(this, [ | |
arguments[0], | |
(...a) => { if(eventsEnabled) arguments[1](...a); }, | |
...arguments.slice(2), | |
]); | |
} | |
return original.apply(this, arguments); | |
} | |
})(window.__proto__.addEventListener); | |
// bonus interceptor for removeEventListener if you want to hook into that as well | |
(function(original) { | |
window.__proto__.removeEventListener = function(type, listener, useCapture) { | |
if(eventWhitelist.includes(type)){ | |
console.log('------> removeEventListener ' + type, listener, useCapture); | |
} | |
return original.apply(this, arguments); | |
} | |
})(window.__proto__.removeEventListener); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment