Last active
September 11, 2024 19:01
-
-
Save notDavid/527feab96bfc27ee5d1df93a82ca3584 to your computer and use it in GitHub Desktop.
A userscript to prevent websites from hijacking browser keyboard shortcuts
This file contains 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 Prevent keyboard shortcut hijacking | |
// @description Prevent websites to hijack keyboard shortcuts, for example <Ctrl+F> on Discourse | |
// @namespace Violentmonkey Scripts | |
// @match *://*/* | |
// @grant none | |
// @version 1.0 | |
// @author notDavid | |
// ==/UserScript== | |
(window.opera ? document.body : document).addEventListener('keydown', function(e) { | |
//alert(e.keyCode ); //uncomment to find more keyCodes | |
var OS="Unknown"; | |
if (navigator.appVersion.toUpperCase().indexOf("MAC")>=0) OS="macOS"; | |
//if (navigator.appVersion.toUpperCase().indexOf("LINUX")>=0) OS="Linux"; | |
//if (navigator.appVersion.toUpperCase().indexOf("X11")>=0) OS="UNIX"; | |
//if (navigator.appVersion.toUpperCase().indexOf("WIN")>=0) OS="Windows"; | |
//console.log(OS); | |
// macOS uses the Command key, identified as metaKey | |
// Windows and Linux use the Control key, identified as ctrlKey | |
//var modifier = (OS == "macOS") ? e.metaKey : e.ctrlKey; | |
var modifier_cmd = e.metaKey; | |
var modifier_ctrl = e.ctrlKey; | |
if (e.keyCode === 116) { | |
// F5 should never be captured | |
e.stopImmediatePropagation(); | |
return; | |
} | |
// abort if modifier isn't pressed | |
if (modifier_cmd || modifier_ctrl) { | |
if (modifier_ctrl) { | |
switch (e.keyCode) { | |
case 70: // f - find | |
e.stopImmediatePropagation(); | |
return; | |
} | |
} | |
if ((OS == "macOS") && (modifier_cmd)) { | |
switch (e.keyCode) { | |
case 188: // , - settings | |
case 82: // r - reload | |
case 70: // f - find (Discourse) | |
e.stopImmediatePropagation(); | |
return; | |
} | |
} | |
} | |
}, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment