Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i am creating an MVC application.There was a neccessitity to make a variable in a session to null upon closing of the application (i.e. window/tab) but not upon refreshing the application. I tried it through the following code.

<script type="text/javascript">
           window.onbeforeunload = function (e) {
               e = e || window.event;
               if (window.event.keyCode == 116) {
                   alert("f5 pressed");
               }
               else {
                   alert("Window closed");
                   //call my c# code to make my variable null, eg:Session["myVariable"] = null;
               }  
           };
</script>

But when F5 is pressed then, "window.event.keyCode" is always 0 and not 116. Because of which my variable is becoming null even upon F5 key press which is not my requirement.

Even when the application (i.e. webpage) is closed,even then its 0 (which is probably correct).

Please note that the above part of the code is in .cshtml file.

Can anyone tell where am i wrong ?

like image 564
ismail baig Avatar asked Feb 05 '13 12:02

ismail baig


2 Answers

You have to listen to different events if you want this to work crossborwser + you have to listen to the key-event every time its pressed, not on load:

document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;

var wasPressed = false;

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

        if (e.keyCode == 116) {
             alert("f5 pressed");
            wasPressed = true;
        }else {
            alert("Window closed");
        }
 }

here is a demo: http://jsfiddle.net/FSrgV/1/embedded/result/

but if you simply want to know if the user quits the page you could simply use window.onbeforeunload: https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

like image 154
meo Avatar answered Sep 20 '22 18:09

meo


Dont use e.keyCode == 116 use e.keyCode == '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. If you go on keycode alone then if the user presses the 't' key your page will refresh.

like image 38
Sim_on Avatar answered Sep 17 '22 18:09

Sim_on