2

I have written some code to block the F5 key on web page. It's working fine except when I have to display a large amount of data. If you press the F5 key during the loading duration in which the HTML and JavaScript code is generated, my page gets refreshed.

Here is the code that I am using to block the F5 key:

document.onkeydown = fn;

var fn = function (e){ 
    if (!e) 
        var e = window.event;
    var keycode = e.keyCode;    
    if (e.which) 
        keycode = e.which;
    var src = e.srcElement;  
    if (e.target) 
        src = e.target;
    // 116 = F5     
    if (116 == keycode) {
        // Firefox and other non IE browsers
        if (e.preventDefault) { 
            e.preventDefault(); 
            e.stopPropagation();
          // Internet Explorer
        }else if (e.keyCode){ 
            e.keyCode = 0; 
            e.returnValue = false; 
            e.cancelBubble = true; 
        } 
            return false; 
    }
});

I think this code is not working when the HTML and JavaScript code is generating.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2533231
  • 21
  • 1
  • 3
  • Shouldn't it be a semicolon on the last line? – Praveen Gowda I V Jun 28 '13 at 20:38
  • 4
    Rather than blocking F5, just warn the user when they leave the page while said process is happening. More often than not they're clicking the refresh button rather than pressing F5 anyway. – Kevin B Jun 28 '13 at 21:20
  • 1
    try this http://stackoverflow.com/questions/2858057/javascript-function-on-web-page-close/2858115#2858115 – Luiz Felipe Jun 28 '13 at 21:42
  • @KevinB If you're forcing full screen like I do on my project which disables F5, you don't need to worry about someone clicking a refresh button because they can't see one. – Jamie Barker May 01 '15 at 10:16

2 Answers2

-1
document.onkeydown=disableF5;
var version = navigator.appVersion;

function disableF5(e) 
{   var keycode = (window.event) ? event.keyCode : e.keyCode;

    if ((version.indexOf('MSIE') != -1)) 
    {  if (keycode == 116) 
       {  event.keyCode = 0;
          event.returnValue = false;
          return false;
       }
    }
    else 
    {  if (keycode == 116) 
          return false;
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
-1

I have some very simple code for preventing F5 that I use myself. Works in IE, Chrome and Firefox:

function disableButtonsDown(e) { 
    if ((e.which || e.keyCode) == 116) e.preventDefault(); 
};
$(document).on("keydown", disableButtonsDown);
Jamie Barker
  • 8,145
  • 3
  • 29
  • 64