40

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.

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
Wasim Shaikh
  • 6,880
  • 18
  • 61
  • 88
  • 1
    possible duplicate of [Javascript function, on web page close](http://stackoverflow.com/questions/2858057/javascript-function-on-web-page-close) – Shoban Feb 16 '12 at 09:13

4 Answers4

66
    window.onbeforeunload = function(event)
    {
        return confirm("Confirm refresh");
    };
bang
  • 4,982
  • 1
  • 24
  • 28
  • 4
    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? – fluxon Mar 27 '13 at 17:44
  • 1
    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... – bang Mar 30 '13 at 17:45
  • 7
    Chrome blocks it – behzad Apr 10 '17 at 10:57
  • 2
    This in an outdated Solution. Confirm block will not work inside the onbeforeunload. https://www.chromestatus.com/features/5349061406228480 – Shiv Kumar Ganesh Jul 23 '18 at 20:54
8
$(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

Riz
  • 9,703
  • 8
  • 38
  • 54
4

the jQuery related event is:

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

Works great for me.

peng37
  • 4,480
  • 1
  • 11
  • 13
Roy Shoa
  • 3,117
  • 1
  • 37
  • 41
4
$(window).bind("beforeunload", function(){
        return confirm("Do you really want to refresh?"); 
});
wintersolutions
  • 5,173
  • 5
  • 30
  • 51