code
code

Reputation: 1081

ESC key safari issue

Is there a better way to redo the following code below? A better approach? When the user hits the ESC key I need the page to redirect them back to their homepage (dashboard screen).

I'm having an issue with the Safari browser though. When a user in Safari hits the ESC key - my server is blocking their IP address (kinda like a brute force protection flag) and I think it's because it's trying to refresh the page over and over again without sending the person back to their dashboard.

The code below works great in Chrome and Firefox...

var keyPressed = {};

document.addEventListener('keydown', function(e) {
  keyPressed[e.keyCode] = true;
}, false);

document.addEventListener('keyup', function(e) {
  keyPressed[e.keyCode] = false;
}, false);

function goToControls() {
  if (keyPressed["27"]) {
    window.location.href = 'home.php';
  }

  setTimeout(goToControls, 5);
}

goToControls();

Upvotes: 0

Views: 708

Answers (1)

code
code

Reputation: 1081

I used the following and it's seems to be happy now!

document.onkeydown = function(evt) {
    evt = evt || window.event;
    var isEscape = false;
    if ("key" in evt) {
        isEscape = (evt.key == "Escape" || evt.key == "Esc");
    } else {
        isEscape = (evt.keyCode == 27);
    }
    if (isEscape) {
        alert("Escape");
    }
};

Upvotes: 1

Related Questions