Search code examples
javascriptreddit

Is there a way to "inject" a custom keyboard shortcut into a page on load?


I'm looking into creating a custom keyboard shortcut for myself browsing reddit.

My plan is to create an event listener to listen for a certain key chord and then toggle a switch in RES. I haven't been able to find a way to "inject"(not sure if I'm using the right word) when I load Reddit.

I would like this shortcut to toggle the Nightmode(or other switches) on keypress.


Solution

  • I found out a way to do it using a Chrome extension called "Tampermonkey".

    Here's the code I used:

        var eventUtility = {
            addEvent : function(el, type, fn) {
                if (typeof addEventListener !== "undefined") {
                    el.addEventListener(type, fn, false);
                } else if (typeof attachEvent !== "undefined") {
                    el.attachEvent("on" + type, fn);
                } else {
                    el["on" + type] = fn;
                }
            }
        };
    
    
        (function() {
            eventUtility.addEvent(document, "keydown",
                function(evt) {
                    var code = evt.keyCode,
                    shiftKey = evt.shiftKey;
    
                    //Shift Key + N
                    if (shiftKey && code === 78) {
                        if(document.getElementById('night mode')){
                            document.getElementById('night mode').click();
                        } else {
                            document.getElementById('RESSettingsButton').click();
    
                            var toggleFilter = function() {
                              document.getElementById('night mode').click();
                            };
                            setTimeout(toggleFilter, 50);
                        }
                    }
                });
        }());