Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when user navigates away from page

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.

like image 795
Nicolai Avatar asked Nov 29 '12 13:11

Nicolai


People also ask

How do I find out if someone is leaving a website?

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.

Which event triggers when the user leaves the page?

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.

What is window Onbeforeunload?

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.

How do I unsubscribe from Beforeunload?

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.


1 Answers

Include the jQuery library in your code, and then try out this

$(window).bind('beforeunload', function(){

        return 'DataTest';
});​

JsFiddle Demo

like image 175
Pranay Rana Avatar answered Sep 27 '22 18:09

Pranay Rana