Capture Browser Or Tab Close Event Jquery Javascript
Posted By : Akash Sharma | 08-Feb-2014
Previously I had a task where I had to hit an ajax call to server on browser close event.
onbeforeunload is an javascript event which occurs on window close but there is a problem with it.
It is bind to all events that occur on window unload like click on a hyperlink , page redirect or page refresh.
Following is the JS code for handling these situations.You need to test this on different browsers before applying.
var validNavigation = false;
function wireUpWindowUnloadEvents() {
/*
* List of events which are triggered onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
// Attach the event keypress to exclude the F5 refresh
$(document).on('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$(document).on("click", "a" , function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$(document).on("submit", "form" , function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]" , function() {
validNavigation = true;
});
$(document).bind("click", "button[type=submit]" , function() {
validNavigation = true;
});
}
function windowCloseEvent()
{
window.onbeforeunload = function() {
if (!validNavigation){
callServerForBrowserCloseEvent();
}
}
}
function callServerForBrowserCloseEvent()
{
//…...Do you operation here
}
For more information you can follow this link .
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Akash Sharma
Akash is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Akash loves playing Cricket and Tennis