简体   繁体   中英

How to check if escape key has been pressed 3 times (like the trevor project website's safety)

I've been trying to make a website for people that feel their life is in danger or anything like that. I'm trying to recreate the Trevor Project's escape key function with javascript.

I have some base code but it's not working:

window.addEventListener("keydown", checkKeyPressed, false);

var escTime = 0;
function checkKeyPressed(evt) {
  if (evt.keyCode === "27") {
    window.clearTimeout();
    escTime++;
    window.setTimeout(function(){
      escTime = 0;
    }, 1000);
  }
  
  if (escTime == 3) {
    window.location.replace("https://classroom.google.com/h");
    escTime = 0;
  }
}

I'd say you're fairly close, but:

  1. You have to remember the handle from setTimeout in order to cancel it, because you have to give it to clearTimeout .

  2. keyCode is deprecated (though unlikely to actually go away), look at key and code instead.

  3. There's no point in assigning 0 back to escTime , the treplace` leaves the page anyway.

So perhaps:

window.addEventListener("keydown", checkKeyPressed, false);

let escapeTimerHandle = 0;
let escapeCount = 0;
function checkKeyPressed(evt) {
    if (evt.key === "Escape" || evt.key === "Esc") {
        clearTimeout(escapeTimerHandle);
        escapeCount++;
        if (escapeCount == 3) {
            window.location.replace("https://classroom.google.com/h");
        } else {
            escapeTimerHandle = setTimeout(function(){
                escapeCount = 0;
            }, 1000);
        }
    }
}

You can accomplish this using a closure :

 function createCheckKeyPressFunction() { let timeout; let escTime = 0; function checkKeyPressed(evt) { if (evt.key === "Escape") { console.log("Escape Detected"); window.clearTimeout(timeout); escTime += 1; timeout = window.setTimeout(()=> { escTime = 0; console.log("Escape count reset to zero, due to timeout."); }, 1000); } if (escTime === 3) { let url = "https://classroom.google.com/h"; console.log(url); window.location.replace(url); escTime = 0; } } return checkKeyPressed; } let checkKeyPressed = createCheckKeyPressFunction(); window.addEventListener("keydown", checkKeyPressed, false);
 <p>Click to give this embedded snippet focus, and then test by hitting the ESC key.</p>

Since the code snippet (above) is embedded in this page, be sure to click into it after running it (to give it focus) before testing it with the Esc key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM