Skip to content

Instantly share code, notes, and snippets.

@Petalousa
Last active June 25, 2021 23:25
Show Gist options
  • Save Petalousa/c15ab23aca84411da2fd37f24772bfef to your computer and use it in GitHub Desktop.
Save Petalousa/c15ab23aca84411da2fd37f24772bfef to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Generic Key Listener
// @namespace http://tampermonkey.net/
// @version 0.1
// @description logs key events. useful for creating a script you want actived on a set of keys
// @author Petalousa
// @include *
// @grant none
// ==/UserScript==
/*
Handles the keyDown events
*/
let onKeyDown = (e) => {
/*
0 = off
1 = on
keyCodeObject outputs the event object of the KeyEvent
keyCode outputs the keyCode of the key thats been pressed
*/
let log = {keyCodeObject: 0, keyCode: 0}
let keyAlt = e.altKey;
let keyCtrl = e.ctrlKey;
let keyShift = e.shiftKey;
if(log.keyCodeObject){console.log(e);}
// https://unixpapa.com/js/key.html
// get the code representation of the key pressed.
let keyCode = e.which === 0 ? e.charCode : e.keyCode;
if(log.keyCode){console.log(keyCode);}
// add cases for keys you want, and hook them up to functions
switch(keyCode){
case 221: // match ']' key
yourFunctionHere();
break;
case 220: // match '\' key
if(keyShift){
console.log(`shift + \\ was pressed`);
}else if (keyAlt){
console.log(`alt + \\ was pressed`);
}else if (keyCtrl){
console.log(`ctrl + \\ was pressed`);
}else{
console.log(`just + \\ was pressed`);
}
break;
default:
//do nothing
}
}
function yourFunctionHere(){
console.log("things")
// Your code here...
}
(function() {
'use strict';
document.addEventListener("keydown", onKeyDown);
console.log("script loaded");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment