Do Javascript function before browser reloads / closes browser / exit page?

Is there a way to execute the function before the user decides to reload / close the browser / exit page?

I need this for the online / offline status function I'm trying to write. I want to determine if the user remains on the page or not.

Any ideas? :)

Maybe there is a better approach to this?

+6
source share
3 answers

Built-in function:

window.onbeforeunload = function(evt) { // Cancel the event (if necessary) evt.preventDefault(); // Google Chrome requires returnValue to be set evt.returnValue = ''; return null; }; 

or through an event listener (recommended):

 window.addEventListener("beforeunload", function(evt) { // Cancel the event (if necessary) evt.preventDefault(); // Google Chrome requires returnValue to be set evt.returnValue = ''; return null; }); 

or if you have jQuery:

 $(window).on("beforeunload", function(evt) { // Cancel the event (if necessary) evt.preventDefault(); // Google Chrome requires returnValue to be set evt.returnValue = ''; return null; }); 

Notes:

When this event returns a non-empty value, the user is prompted to confirm the page is unloaded. In most browsers, the event return value is displayed in this dialog.

As of May 25, 2011, the HTML5 specification states that calls to window.showModalDialog (), window.alert (), window.confirm (), and window.prompt () can be ignored during this event.

See the documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

+18
source

Try the following:

 $( window ).unload(function() { alert( "Handler for .unload() called." ); }); 

OR this if you want to notify about conformation

 <script> window.onbeforeunload = function(e) { return 'Your dialog message'; }; </script> 
0
source

All Articles