Open Window When User Leaves Site
We just ran into a situation where we had a legitimate reason to display a popup window when a visitor was leaving a website either by closing the browser window or by navigating to an external site. After much searching we found there was no solution that would work 100%, even this solution does not work 100% but we got it close enough that we are happy with it.
The Problem
We want to pop open a window which contains a survey when a visitor leaves the site either by external link or by closing the browser window.
Solution #1 – External Links
This is the easy one. We simply create a class and tag each external link on the site with class=”external”. ( We know that we could have used a[target="_blank"], but didn’t work for our situation)
Code
JS
$(document).ready(function() {
$('a.external').click(function(){ alert('Display Survey') });
});
HTML
<a href="http://www.google.com" class="external">Visit Google</a>
Solution #2 – On Browser Close
Since there is no function specifically for when a user clicks the close browser button it makes this a bit tough to achieve this task. We know we needed to use $(window).unload but that would always throw our alert every time we left a page. Below is what we came up with.
Code
JS
var internalLink = false;
$(document).ready(function() {
$('a').not('.external').click(function(){ internalLink = true; });
});$(window).unload(
function () {
if(!internalLink){
alert('Display Survey');
}
}
);
Final Thoughts
So combining both of these solutions worked and got us to about 95% success rate for reaching our goal. The only downfall that we came up with is that if a viewer presses the refresh button the alert is thrown. If anyone has any thoughts on how to work around this please post a comment and let us know.
We hope this snippet can save someone a couple hours of digging on the internet!

As much as I feel that the popup onclose is really cheesy the results that WTW shows are pretty incredible that someone could increase sales by 62.6% by adding a chat window popup when the leave the site.
Nice, I was just thinking about this the other day. WhichTestWon recently did an A/B test on a page with a chat popup (on close). http://whichtestwon.com/chat-test/
Yes it does work when a viewer presses the back button to leave the site. The script uses the command onUnload so every time someone leaves the page no matter how they do it the page is unloaded.
Awesome tips! Wondering… does it work when the user clicks the back button to leave the site?