Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 332
Rajat Shah Avatar asked Jun 07 '26 04:06

Rajat Shah


1 Answers

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.

like image 75
ThiefMaster Avatar answered Jun 10 '26 18:06

ThiefMaster