views:

24

answers:

2

I have a website (written in PHP) that my users need to log into, and I want to be sure that they log out when they're done. So, I have a JavaScript method that deletes the PHP session cookies, and I want to call that method (a) right before the user either closes the browser window (i.e., the DOM Window object) or (b) points their browser to a site outside of my domain. Part (a) is pretty simple using the Window.onclose method, but I can't figure out how to do part (b). The problem is that I can't get any of the Window events to distinguish between when the user is leaving my domain and when he's going to a different page in my domain. I've seen this on some websites (like, banking website for example) but does anyone know how I'd actually implement it?

Thanks.

A: 

This blog post is about just that.

If you're using prototype, the code will look something like this. (taken from blog post)

staying_in_site = false;

Event.observe(document.body, 'click', function(event) {
  if (Event.element(event).tagName == 'A') {
    staying_in_site = true;
  }
});

window.onunload = popup;

function popup() {
  if(staying_in_site) {
    return;
  }
  alert('I see you are leaving the site');
}
NixNinja
Seems like I'm 90% there. The only problem is that when the page is refreshed, I get the alert even though I'm not leaving the site.
jay
+1  A: 

Also, this is approximately the code from that blog post, but written with jQuery (which is what I'm using):

var stay_in_site = false;
$('a').live('click', function() {
    stay_in_site = true;
}

window.onunload = function() {
    if(stay_in_site) {
        return;
    }
    alert("I see you are leaving the site.");
}
jay

related questions