Javascript: Display message when user leaves site
- by Brian Rasmusson
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.