Warm tip: This article is reproduced from serverfault.com, please click

Notify user on browser close only

发布于 2013-08-19 09:30:48

I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;

This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it. But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way. Is there a way to catch the refresh or browser cosing so that can use it.

Questioner
Deepu
Viewed
0
T.J. Crowder 2017-11-26 18:20:04

Note that in your code, you're using onbeforeclose, but the event name is beforeunload, so property is onbeforeunload, not onbeforeclose.

I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.

No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).

For example:

var warnBeforeClose = true;
function unloadPage(){
    if (warnBeforeClose) {
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn
    warnBeforeClose = false;

    // ...but if we're still on the page a second later, set the flag again
    setTimeout(function() {
        warnBeforeClose = true;
    }, 1000);
}

Or without setTimeout (but still with a timeout):

var warningSuppressionTime = 0;
function unloadPage(){
    if (+new Date() - warningSuppressionTime > 1000) { // More than a second
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn for the next second
    warningSuppressionTime = +new Date();
}

Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.