Detect Page Start and Navigation Away in jQuery
This quick snippet of jQuery that will allow you to so do something before the user navigates away from a page or closes the browser or tab.
In this example I have mixed in some JavaScript Date functionality to give a timer of how long you were on the page.
// get the starting date
var start = new Date();
var timeStart = 0;
// capture the start time with a mouseover on the document body
$(document).ready(function(){
$("body").mouseover(function(){
if (timeStart==0) {
timeStart = start.getTime();
}
});
});
// bind a function to the window closing
$(window).bind("beforeunload", function(){
alert("Leaving so soon? You were only here for "+timer()+" seconds.");
});
// ask the user to confirm the window closing
window.onbeforeunload = function() {
return "Leaving so soon? You were only here for "+timer()+" seconds.";
}
// function to get the starting date
function timer() {
var end = new Date();
var timeEnd = end.getTime();
return((timeEnd-timeStart)/1000);
}
Bookmark/Search this post with:

Comments
this works good to me. However i just want to handle browser window close event not the navigation. Actually when user closes his browser window without hitting the log out button i wanted to send a server request to abandon users session. Could you please let me know the way i can achieve this?
The browser or tab being closed and navigating to a new page are both the same thing as far as the browser is concerned.
The way I handled it was to add a disable switch to each link and form. This left external links and closing the browser as the only events where this was triggered.
I wanted to show a message box to users who are leaving from my site. When they are try to leave.. changing url or closing browser. Message box is a div area. I did this with onbeforeunload . In this case , div area was shown and suddenly redirecting to users targeting page. I want to stop the page loading and show the pop-up . The message box is give option to leave or stay. Please help me..
I don't think you can stop the unload action. Perhaps you can do it with an alert(), or perhaps returning false in the right place would help. If you find out I would be interested to know your solution.
Nice work with your coding.
Cheers,
-Baby Cot
Post new comment