0

Possible Duplicate:
javascript detect browser close tab/close browser

Does anyone know a reliable way to listen out for a window closing event in javascript/ jQuery?

The window is the parent and not any child instances. I.e. if a window is closed by mistake and the visitor launches their browser again and loads the url previously visited once more.

Community
  • 1
  • 1
James Radford
  • 1,815
  • 4
  • 25
  • 40

2 Answers2

2

You can use the window.unload event to set a cookie or use local storage to save the time using new.date(), then see if the visitor returned within a set amount of time.

Something like:

$(window).unload(function() {
    localStorage.setItem(“theyLeft”, new Date());
}

then on load check for :

$(window).load(function() {
    var timeGoneBy = new Date() - localStorage.getItem(“theyLeft”);
    //calculate time gone by, and do something if visitor returned within given time etc.
}

Would need to be refined a lot, and local storage should have cookies as fallback, but just to show the jist of it.

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Try the unload method.

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

You can also try playing with the JS onunload and onbeforeunload events.

Shomz
  • 37,421
  • 4
  • 57
  • 85