Wasim Shaikh
Wasim Shaikh

Reputation: 7030

Execute function before refresh

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.

Upvotes: 43

Views: 86759

Answers (4)

Roy Shoa
Roy Shoa

Reputation: 3195

the jQuery related event is:

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

Works great for me.

Upvotes: 3

Riz
Riz

Reputation: 10246

$(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

Upvotes: 8

wintersolutions
wintersolutions

Reputation: 5283

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

Upvotes: 4

bang
bang

Reputation: 5221

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

Upvotes: 69

Related Questions