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?
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.
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.
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.
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.
$(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,
...
});
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
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