Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when a user has left the page and refreshed the page

I want to make an AJAX call before the user leaves the page (so basically before leaving the page and before refreshing the page)?

How can this be done. I was trying to search something with jQuery but didnt get anything.

I tried to use the following code -

window.onbeforeunload(function(){alert('before unload');});

But the alert box never appears when leaving the page(closing the browser tab) or refreshing the page.

How can this be accomplished?

like image 529
Siddharth Avatar asked Jul 25 '11 20:07

Siddharth


People also ask

How do you detect if the user has left the page?

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.

How do you find a leaving page?

Here's an alternative solution - since in most browsers the navigation controls (the nav bar, tabs, etc.) are located above the page content area, you can detect the mouse pointer leaving the page via the top and display a "before you leave" dialog.

How do I know if my browser is close or refresh?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.


3 Answers

You should try unload() from jquery:

$(window).unload(function(){
   //Do your call
   alert('before unload');
  });

oro you could use the beforeunload event. You should test it well because browser tend to imlement those things differently. taken from jquery documentation:

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

like image 184
Nicola Peluchetti Avatar answered Sep 18 '22 18:09

Nicola Peluchetti


$(window).unload(function() {
    alert('Visitor left page');
});

Regarding the ajax call, you can do it, but you must set the async to false.

$.ajax({
   async: false,
   ...
 });
like image 34
Shef Avatar answered Sep 18 '22 18:09

Shef


Your code is simply wrong. The unbeforeunload is used to ask the person if he really want to leave the page. You need unload.

window.onunload = function() {
  // Make your AJAX call

}

Better use jQuery.unload() method

like image 35
Claudio Avatar answered Sep 22 '22 18:09

Claudio