Skip to content

Instantly share code, notes, and snippets.

@Carpetfizz
Last active June 10, 2016 10:46
Show Gist options
  • Save Carpetfizz/4fab48c73cbae82d5c54eb0a6966b472 to your computer and use it in GitHub Desktop.
Save Carpetfizz/4fab48c73cbae82d5c54eb0a6966b472 to your computer and use it in GitHub Desktop.
Listen for characters typed into your website to invoke a function

   cheatcode.js Just a late night hack. Usage like so:

var c = new CheatCode();
c.register("drizzydrake", function(){
  console.log("6!x");
});

c.register("ArrowLeftArrowRightArrowLeft", function(){
  // do something cool, or waste the user's time
  console.log("you probably have work to do")
});

//TODO:

  • add a timeout option. currently you can wait until the heat death of the universe to type the last letter and it'll still work
function CheatCode(){
this._lettersPressed = [];
this._registeredWords = [];
var _getLastN = function(n, a){
var r = [];
for(var i=0; i<n; i++){
r.push(a[a.length - i -1])
}
return r.reverse();
}
window.addEventListener("keydown", function(e){
this._lettersPressed.push(e.key);
for(var i=0; i<this._registeredWords.length; i++){
var registeredWord = this._registeredWords[i];
if(_getLastN(registeredWord.word.length, this._lettersPressed).join("") == registeredWord.word){
registeredWord.event.call(registeredWord.event, registeredWord.word);
this._lettersPressed = [];
}
}
}.bind(this));
}
CheatCode.prototype.register = function(w, e){
this._registeredWords.push({word: w, event: e});
}
@tenacex
Copy link

tenacex commented Jun 9, 2016

Could you explain the purpose of this hack? I'm just curious for a real use case example.

@Carpetfizz
Copy link
Author

Yeah! Sorry for the vague readme. Some sites hide easter eggs by having the user type a secret code into the site before revealing them. For example there are konami code websites which only do something when a specific keystroke is entered onto the site. cheatcode.js makes creating those types of easter eggs easier.

@rgajrawala
Copy link

rgajrawala commented Jun 10, 2016

Some problems:

new CheatCode().register("travi$", function() {
  console.log("called!");
}); // never called

new CheatCode().register("activatecheat", function() {
  throw new Error("Whoops!");
}); // `this._lettersPressed = [];` never executes

Some features to add:

new CheatCode().register("hi1", function() {
  console.log("hi1");
}).register("hi2", function() {
  console.log("hi2");
}); // method chaining

new CheatCode().register("travi$", function() {
  console.log("6!x");
}, function() {
  console.log("8 god");
}); // multiple handlers

Other comments:

  • Any reason you are using func.call(func, ...) over func(...)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment