How can I detect when the user is leaving my site, not just going to a different page?
It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:
window.localLinkClicked = false;
$("a").live("click", function() {
var url = $(this).attr("href");
// check if the link is relative or to your domain
if (! /^https?:\/\/./.test(url) || /https?:\/\/yourdomain\.com/.test(url)) {
window.localLinkClicked = true;
}
});
window.onbeforeunload = function() {
if (window.localLinkClicked) {
// do stuff
} else {
// don't
}
}