Skip to content

Instantly share code, notes, and snippets.

@Sv443
Created June 2, 2023 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sv443/b2768fdebc8a037fbde4f4df9f7443a2 to your computer and use it in GitHub Desktop.
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
// ==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