73

I want to disable browser refreshing using JavaScript.

Currently, I am using window.onbeforeunload and I don't want it to be called when user refreshes the browser.

What is the best way to do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Salil
  • 46,566
  • 21
  • 122
  • 156

11 Answers11

100

Update A recent comment claims this doesn't work in the new Chrome ... As shown in jsFiddle, and tested on my personal site, this method still works as of Chrome ver 26.0.1410.64 m

This is REALLY easy in jQuery by the way:

jsFiddle

// slight update to account for browsers not supporting e.which
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5
    /* jQuery < 1.7 */
$(document).unbind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).off("keydown", disableF5);

On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes. Can't say I really know how to do this as I haven't done it yet.

On the software site that I work at, we use my disableF5 function in conjunction with Codeigniter's session data. For instance, there is a lock button which will lock the screen and prompt a password dialog. The function "disableF5" is quick and easy and keeps that button from doing anything. However, to prevent the mouse-click on refresh button, a couple things take place.

  1. When lock is clicked, user session data has a variable called "locked" that becomes TRUE
  2. When the refresh button is clicked, on the master page load method is a check against session data for "locked", if TRUE, then we simple don't allow the redirect and the page never changes, regardless of requested destination

TIP: Try using a server-set cookie, such as PHP's $_SESSION, or even .Net's Response.Cookies, to maintain "where" your client is in your site. This is the more Vanilla way to do what I do with CI's Session class. The big difference being that CI uses a Table in your DB, whereas these vanilla methods store an editable cookie in the client. The downside though, is a user can clear its cookies.

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • Hello dear, You code is really great I try in my one of page and it's disable all autopostback for my all control on that page. After that I remove these line of code. But autopostback not enable. I restart my machine clear all browser history but autopostback not enable at all. What is reason behind that. Please guide me. – Saroop Trivedi Feb 08 '13 at 07:10
  • 2
    @alem0lars after extensive testing, i found this function still works in Chrome just fine. perhaps we can see some of your other code? [See working example in Chrome HERE](http://jsfiddle.net/SpYk3/C85Hs/). As you can see it works fine and your Down vote was really unnecessary. – SpYk3HH May 06 '13 at 17:18
  • This is really cool, but I have a question. `Ctrl+Shift+R` is for hard reload, similarly `Ctrl+R` or `F5` is for normal reload. I have seen some sites give the option to do all of them after **long press of the reload button**. Yes we can block these keys, but how can we block that menu from popping for a specific site/page? – Code_Ninja Jul 12 '18 at 12:09
  • You'll probably also want to add cases for Ctrl+F5 and Ctrl+R. Also, most browsers allow refreshing from the context menu. Not much you can do here besides disabling the context menu all together, which in most cases is something to avoid. – Dimitri Troncquo Jun 22 '21 at 20:10
  • Of course, this doesn't disable refreshing at all. It merely blocks the F5 key, if the document has focus. Saying "This is REALLY easy in jQuery" is disingenuous at best. – Heretic Monkey Jul 29 '21 at 15:24
11
var ctrlKeyDown = false;

$(document).ready(function(){    
    $(document).on("keydown", keydown);
    $(document).on("keyup", keyup);
});

function keydown(e) { 

    if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown)) {
        // Pressing F5 or Ctrl+R
        e.preventDefault();
    } else if ((e.which || e.keyCode) == 17) {
        // Pressing  only Ctrl
        ctrlKeyDown = true;
    }
};

function keyup(e){
    // Key up Ctrl
    if ((e.which || e.keyCode) == 17) 
        ctrlKeyDown = false;
};
Jos
  • 111
  • 1
  • 2
11

Enter this simple script in pure JS:

document.addEventListener('keydown', (e) => {
    e = e || window.event;
    if(e.keyCode == 116){
        e.preventDefault();
    }
});
Blackjack
  • 1,322
  • 1
  • 16
  • 21
9

From the site Enrique posted:

window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
    }
}
kzh
  • 19,810
  • 13
  • 73
  • 97
  • Keep in mind, this doesn't disable the `Back Button`. The 1st line [`window.history.forward(1);`] is meant to be put on EVERY page you don't want user to go `back` to. Simply put, if user hits back, they are redirected to were they are. This really only works with `linear sequence` pages, such as banking sign ins. The rest is just Vanilla JS of the jQuery Method I spoke of in my answer. Most places have replaced the first line with either a server side redirect, or something like Node.JS which allows for *live calls*, like sockets, keeping constant *tabs* on what the user is doing. Much easier – SpYk3HH Feb 19 '14 at 13:47
7

for mac cmd+r, cmd+shift+r to need.

function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
$(document).on("keydown", disableF5);
});
gokhan
  • 665
  • 2
  • 9
  • 16
6

Use this for modern browsers:

function my_onkeydown_handler( event ) {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.preventDefault();
            event.keyCode = 0;
            window.status = "F5 disabled";
            break;
    }
}
document.addEventListener("keydown", my_onkeydown_handler);
MadPapo
  • 495
  • 4
  • 13
Orhun Alp Oral
  • 734
  • 1
  • 7
  • 14
5

This is the code I'm using to disable refresh on IE and firefox which works for the following key combinations:

F5   |   Ctrl + F5   |   Ctrl + R

//this code handles the F5/Ctrl+F5/Ctrl+R
document.onkeydown = checkKeycode
function checkKeycode(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
                
    // Mozilla firefox
    if ($.browser.mozilla) {
        if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
            if (e.preventDefault)
            {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    } 
    // IE
    else if ($.browser.msie) {
        if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
            window.event.returnValue = false;
            window.event.keyCode = 0;
            window.status = "Refresh is disabled";
        }
    }
}

If you don't want to use useragent to detect what type of browser it is ($.browser uses navigator.userAgent to determine the platform), you can use

if('MozBoxSizing' in document.documentElement.style) which returns true for firefox

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Saurav S.
  • 177
  • 3
  • 3
  • Please don't post identical answers to separate questions. If the questions are duplicates, flag one as a duplicate of the other (or leave a comment to that effect). Otherwise, please tailor your answer to the question asked. – George Stocker Nov 14 '12 at 12:27
  • 1
    but what if user clicks the refresh button – Chetan Mar 21 '13 at 07:12
5
$(window).bind('beforeunload', function(e) { 
    return "Unloading this page may lose data. What do you want to do..."
    e.preventDefault();
});
epoch
  • 16,396
  • 4
  • 43
  • 71
Hla Min Swe
  • 291
  • 3
  • 5
  • 10
    This doesn't event make sense. You have unreachable code after the return point. – Chris_F Dec 01 '16 at 00:54
  • It kind of works for me on firefox, but not chrome. Feel like this could be a more useful answer if elaborated on to robustly work. –  Feb 23 '18 at 17:10
3

It works for me in all the browsers:

document.onkeydown = function(){
  switch (event.keyCode){
        case 116 : //F5 button
            event.returnValue = false;
            event.keyCode = 0;
            return false;
        case 82 : //R button
            if (event.ctrlKey){ 
                event.returnValue = false;
                event.keyCode = 0;
                return false;
            }
    }
}
2

If you want to disable ctrl+f5 , ctrl+R , f5 ,backspace then you can use this simple code. This code is working in Mozila as well as Chrome . Add this code inside your body tag:

<body onkeydown="return (event.keyCode == 154)">
0

You can directly use hotkey from rich faces if you are using JSF.

<rich:hotKey key="backspace" onkeydown="if (event.keyCode == 8) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="f5" onkeydown="if (event.keyCode == 116) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+R" onkeydown="if (event.keyCode == 123) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+f5" onkeydown="if (event.keyCode == 154) return false;" handler="return false;" disableInInput="true" /> 
pratik
  • 19
  • 1