How do I detect that a user is navigating away from my page? Kind of like stackoverflow does, if you have started writing a post.
I have tried $(window).unload()
in jQuery, but I can't get it to work.
This statement is not entirely true, in IE9 it works, in fact a bit too well. It also pops up, if the page is refreshed. But in Chrome, nothing triggers.
The most reliable way to detect when a user leaves a web page is to use visiblitychange event. This event will fire to even the slightest changes like changing tabs, minimizing the browser, switching from browser to another app on mobile, etc. More info about this event can be found on MDN.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.
Include the jQuery library in your code, and then try out this
$(window).bind('beforeunload', function(){
return 'DataTest';
});
JsFiddle Demo
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