Popup when leaving website
On my current project, we had a requirement to pop up a message to the user when they leave our site (e.g., close the browser window). We discovered a number of sites talking about a window.close event, but it is not supported in modern browsers (IE 6, Firefox 2, Safari 2). The closest event is an unload event which gets fired when the page is unloaded.
We tried using this event in a javascript file that is included on every page:
window.onunload = popup;
function popup() {
alert('I see you are leaving the site');
}
Unfortunately, an unload event is fired when the user leaves the page for any reason (such as clicking on a link). We did not want to show the popup if the user clicked on a link which stayed on the site.
Our next idea was to add an onclick to every link which would turn off the popup. Then, if the user clicks a link, nothing happens. If they leave the site another way, they get the popup.
Toby Tripp had the great idea to add these onclicks dynamically in javascript. We use prototype, so the code looks like:
staying_in_site = false;
$$('a').each(function(link) {
link.observe('click', function() {staying_in_site = true;});
});
window.onunload = popup;
function popup() {
if(staying_in_site) {
return;
}
alert('I see you are leaving the site');
}
This code creates a variable which determines whether or not to show the popup. Then, we find every link with $$(‘a’). This is a CSS selector which selects all of the a elements. We iterate over these links and add a listener which sets the staying_in_site flag to true. Now, our popup code checks this flag and knows whether the user is staying on the site.
It is important to include this javascript at the bottom of the file (and not in the head). The javascript must be executed after the page is written or the links will not exist yet.
This solution is not perfect, but it accomplishes most of what we need.
Update (1/31/08): Simon Stewart suggested a cleaner method in the comments:
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');
}
Instead of attaching an event listener to every link, we can attach a click listener to the whole body. Now, any click will call our function, which checks to see if you clicked on a link. Since we are not iterating over existing links, this javascript does not have to be below the links in the page.