0

I am trying to stop the user from navigating away from the page while they are inputting some text. I am doing this by suppressing the F5 button and the backspace button, which goes back.

Now I notice that I cannot press t. When I check the logs, it's because t is giving me a key event code of 116 which is the same as the F5 button.

How can I get around this?

Here is a code snippet.

function suppressBackspaceAndF5(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;

    // when I release "t" - the code is 116, which is the same as the refresh code.
    console.log(evt.keyCode);

    if ((evt.keyCode == 8 && 
         !/input|textarea/i.test(target.nodeName)) || 
         evt.keyCode == 116) {
            return false;
    }
}

document.onkeydown = suppressBackspaceAndF5;
document.onkeypress = suppressBackspaceAndF5;
<input></input>
Oshadha
  • 546
  • 10
  • 25
Ogen
  • 6,499
  • 7
  • 58
  • 124

1 Answers1

1

I found this related Stackoverflow question which seems to contains your answer. Posting here specifically as a reference:

capturing f5 keypress event in javascript using window.event.keyCode in window.onbeforeunload event is always 0 and not 116

Excerpt: by SO user Sim_ba

Dont use e.keyCode == 166 use e.code == 'F5' instead.

function fkey(e){
e = e || window.event;
if( wasPressed ) return; 

function fkey(e){
    e = e || window.event;
    if (e.code === 'F5') {
        alert("f5 pressed");
        wasPressed = true;
    }else {
        alert("Window closed");
    }
}

This is because the 't' and 'F5' both use the keycode number 116. [...]

Go vote Sim_ba up as well! :)

Community
  • 1
  • 1
ryancdotnet
  • 2,015
  • 16
  • 33