Execute function before refresh

62,812

Solution 1

    window.onbeforeunload = function(event)
    {
        return confirm("Confirm refresh");
    };

Solution 2

$(window).bind('beforeunload', function(){
    return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});

Source: http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/

Demo: http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-stop-page-from-exit.html

Solution 3

$(window).bind("beforeunload", function(){
        return confirm("Do you really want to refresh?"); 
});

Solution 4

the jQuery related event is:

$( window ).on('unload', function( event ) {
    console.log('Handler for `unload` called.');
});

Works great for me.

Share:
62,812
Wasim Shaikh
Author by

Wasim Shaikh

I am HTML and CSS Coder

Updated on March 30, 2020

Comments

  • Wasim Shaikh
    Wasim Shaikh about 4 years

    On my HTML page, when the user clicks / presses F5 button the page refreshes, but before it refreshes I want to execute a function or a simple alert.

    User can click on refresh button, press F5 or Ctrl + R.

    Using core JavaScript, jQuery or YUI.

  • fluxon
    fluxon about 11 years
    Well, for me this does not solve the problem described. It triggers the confirm box (with a predefined and probably browser specific text) on all events leaving the page. I.e., also on form-submission. There it is really irritating and not intended! Any thoughts?
  • bang
    bang about 11 years
    Then you need to explain som more about whats specific about your problem... Show us some code (jsfiddle ?) and tell us what browser your using...
  • behzad
    behzad about 7 years
    Chrome blocks it
  • Shiv Kumar Ganesh
    Shiv Kumar Ganesh almost 6 years
    This in an outdated Solution. Confirm block will not work inside the onbeforeunload. chromestatus.com/features/5349061406228480