views:

206

answers:

2

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.

+4  A: 

I will start by saying that I will not, in any way, recommend that you do this. It's a bad practice, it only annoys users and it makes you look extremely desperate. I repeat, don't do this, it's not a good idea, it's silly and it's not a good idea.

But the way you can do it is to only display the message when users are clicking on links that lead away from the site. You can do this by looking at the href attribute of the link and check if it's an external site. If it is, then display the message

But I repeat, don't do this!

henrikh
Guys, don't tell me what to do and what not to do. I didn't know the "moral police" was monitoring this forum :-)Seriously, since you don't know what I am going to present in this window you shouldn't dismiss what I want to do so fast. I believe in testing, and this is for a test.
JubbaJubba
A: 

We might be able to forgive you for window.onbeforeunload. But that's it!

icio