0

I'd like to know that a user leave from a Web page. I think there might be three scenarios: 1. move to another page in the same Web site, either open a new window or load a new page to the current window, 2. move to a page in different site, and 3. close the window.

Based on these scenarios, what I'm thinking is to check whether the current window is the focus. So my first question is Is this the right way? And the second question is How should I implement it in javascript?

Paul
  • 954
  • 19
  • 34
  • 1
    Duplicate http://stackoverflow.com/questions/147636/best-way-to-detect-when-user-leaves-a-web-page – cletus Oct 25 '09 at 03:46

3 Answers3

4

Take a look Mastering The Back Button With Javascript (it's the same principle). There are two relevant events: unload and beforeunload. Also see Best way to detect when user leaves a web page.

Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942
  • I believe you meant: http://www.codetoad.com/javascript/miscellaneous/onunload_event.asp – Daren Schwenke Oct 25 '09 at 03:42
  • take note: beforeunload you can't add in additional javascript code. it only allows you to return a string, which will be displayed by the browser – mauris Oct 25 '09 at 03:53
1

I just want to comment that there is probably no reliable, cross-browser solution for this... I know this doesn't add much value to your question, but if you can resolve your problem in any other way, I think it would be also more ergonomic.

0

You can't detect opening a new window or tab, but you can listen for the 'onunload' event.

jQuery(window).bind("unload", function() {
    //your code here
}); 

This should fire when clicking on a link, closing the tab/window or pressing the back button.

Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63