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!
-
http://leadgenseo.com A Really Cool Guy
-
http://www.e-moxie.com Matt Pramschufer
-
http://www.robspangler.com/ Robert Spangler
-
http://www.e-moxie.com Matt Pramschufer