Is there a way to execute a function before a user chooses to reload/close browser/exit page?
I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.
Any ideas? :)
Maybe there is a better approach to this?
Inline function:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
or via 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-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog.
Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.
See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With