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.
Note that in your code, you're using
onbeforeclose, but the event name isbeforeunload, so property isonbeforeunload, notonbeforeclose.No. Instead, you'll have to capture each link and form submission and either set a flag telling your
onbeforeunloadhandler not to return a string, or removing youronbeforeunloadhandler (probably the flag is cleaner).For example:
Or without
setTimeout(but still with a timeout):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
nullas a flag to show their own, built-in message instead.