Execute function before refresh
Asked Answered
E

4

43

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.

Eucalyptol answered 16/2, 2012 at 9:10 Comment(1)
possible duplicate of Javascript function, on web page closeEncratia
O
69
    window.onbeforeunload = function(event)
    {
        return confirm("Confirm refresh");
    };
Odel answered 16/2, 2012 at 9:12 Comment(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?Bird
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...Odel
Chrome blocks itCarducci
This in an outdated Solution. Confirm block will not work inside the onbeforeunload. chromestatus.com/features/5349061406228480Spode
I
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

Impassable answered 16/2, 2012 at 9:12 Comment(0)
T
4
$(window).bind("beforeunload", function(){
        return confirm("Do you really want to refresh?"); 
});
Teacher answered 16/2, 2012 at 9:14 Comment(0)
D
3

the jQuery related event is:

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

Works great for me.

Dufrene answered 29/6, 2017 at 9:30 Comment(1)
The question is for 'before' unload, this event will not work for that, read the docs: developer.mozilla.org/en-US/docs/Web/API/Window/unload_eventContrary

© 2022 - 2024 — McMap. All rights reserved.