Display message when user leaves site

Posted by Brian Rasmusson on Stack Overflow See other posts from Stack Overflow or by Brian Rasmusson
Published on 2010-05-02T14:55:03Z Indexed on 2010/05/02 15:37 UTC
Read the original article Hit count: 317

Filed under:
|

Hi,

I'm looking for a way to display a message to the user if he leaves my site after only viewing one page.

I found this (http://www.pgrs.net/2008/1/30/popup-when-leaving-website) clever solution, but it has a few flaws:

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');
}

It displays the message also when refreshing the page or using the back button.

Do you know a better solution or how to fix it in the above code? I'm no javascript master :)

My intention is to add the code on very specific landing pages only, and display the message when people leave the page without downloading my trial software or reading other pages on my site.

© Stack Overflow or respective owner

Related posts about popupwindow

Related posts about JavaScript