16

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 ?

ismail baig
  • 861
  • 2
  • 11
  • 39
  • you are storeing your event into the variable e. Why don't you try `e.keyCode` ;) And the event you should listen to is the keyPress event. – meo Feb 05 '13 at 12:33
  • hi meo: i already have tried it but i get the same result. Then i tried the above mentioned code, but still in **vain**. – ismail baig Feb 05 '13 at 12:38
  • 2
    You cant set Session variables in javascript... – Steve Feb 05 '13 at 12:38
  • If you are looking to do session stuff client side, maybe you should look at sessvars.js http://www.thomasfrank.se/sessionvars.html – Steve Feb 05 '13 at 12:40
  • Doesn't `e.keyCode` apply only to keyboard events? (Also, even if it did apply, you should test `e.keyCode` in your `if` statement, not `window.event.keyCode`.) – nnnnnn Feb 05 '13 at 12:40
  • @Steve: Thanks, you are right, i just wanted to show the sample so i did that way. but now i have edited my question accordingly. – ismail baig Feb 05 '13 at 12:42
  • F5 is not the only way a user can refresh the page... – JJJ Feb 05 '13 at 12:42
  • @Juhana: yes, user can also use Ctrl + R, but first i was not able to capture F5 itself which is most obvious way. If i could then i will also add condition for "Ctrl + R". – ismail baig Feb 05 '13 at 12:45
  • What are you going to do about clicking the reload button? – JJJ Feb 05 '13 at 13:00
  • Final conclusion: (i am adding this comment as it could be helpful to others). the **"window.event.keyCode"** is always **0** by the time the code control reaches **"window.onbeforeunload"**.So please use it wisely. – ismail baig Feb 06 '13 at 05:29
  • Actually there is a way to set a session variable from javascript , and that's to call a controller method via jS that does that. I've done it before. (sorry if too late or a bit off topic) – LeoGranata Nov 23 '18 at 18:43

7 Answers7

25

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

meo
  • 30,872
  • 17
  • 87
  • 123
11

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.

xlm
  • 6,854
  • 14
  • 53
  • 55
Sim_on
  • 164
  • 1
  • 11
4

You could just write it like this:

$(document.body).on("keydown", this, function (event) {
    if (event.keyCode == 116) {
        alert('F5 pressed!');
    }
});
yergo
  • 4,761
  • 2
  • 19
  • 41
Paul
  • 41
  • 1
4
document.onkeydown = disableF5;
document.onkeypress = disableF5
document.onkeyup = disableF5;    
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
Shaz
  • 419
  • 3
  • 11
1

Modified version and working also after pressing 't'.

key 116 getting pressed auto after 84

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");

    }else {
        alert("Window closed");
    }
    wasPressed = true;
}
Faisal Shahzad
  • 694
  • 9
  • 13
1

dont use (e.keyCode == 116) to ckeck F5 ; instead of use this

<script>
    document.onkeydown = capturekey;
    document.onkeypress = capturekey;
    document.onkeyup = capturekey;

    function capturekey(e) {
        e = e || window.event;
        //debugger
        if (e.code == 'F5') {
            if (confirm('do u wanna to refresh??')) {
                //allow to refresh
            } 
            else {
                //avoid from refresh
                e.preventDefault()
                e.stopPropagation()
            }
        }
    }
</script>
R.Akhlaghi
  • 729
  • 1
  • 12
  • 23
0

I agree with meo's solution, but I will add some modifications.

when we use document.onkeydown = fkey; for example and in the page we have another method affected to the document.onkeydown then the browser will detect only the last event. However when we use : jQuery(document).on("keydown",fkey); even if we have another function to handle the keydown event, all the functions will be triggered.

see the next example to more understand:

var wasPressed = false;
document.onkeydown = f1;
document.onkeydown = f2;

jQuery(document).on("keydown",f3); 
jQuery(document).on("keydown",f4); 
function f1(e){
e = e || window.event;
if( wasPressed ) return; 

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

what will be shown here: only 3 alerts: f2,f3 and f4. and the f1 function isn't triggred in this example.

senior
  • 2,196
  • 6
  • 36
  • 54