Search code examples
javascriptonbeforeunload

Call a function on page refresh using Javascript


function warnuser()
{
    return "Don't refresh the page.";
}

window.onbeforeunload = warnuser;

If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not! I am confused about how to do that. Thank you


Solution

  • You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:

    document.addEventListener('keydown', function(e) {
        if(e.which == 116) {
            window.onbeforeunload = function() {
                window.onbeforeunload = null;
                return "Do you really want to refresh the page?";
            }
        }
    }, false);
    

    Demo: http://jsfiddle.net/ejDrq/

    Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.