Skip to content

Instantly share code, notes, and snippets.

@bes89
Forked from abits/exit-notice.html
Created July 14, 2012 16:39
Show Gist options
  • Save bes89/3112071 to your computer and use it in GitHub Desktop.
Save bes89/3112071 to your computer and use it in GitHub Desktop.
Do stuff when user exits site.
<!-- This is a short demo how js could detect whether a user wants to leave the site.
Tested with Firefox and Chrome. (c) Christoph Martel <[email protected]> -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
/* flag signaling whether the user wants to leave the site;
needs to default false to exclude page reloads or true to include
cases where user entered new url in tab */
var leaving = false;
var allowedDomain = 'yourdomain.com';
/* bind all clicks to links to a is_leaving function */
$(document).ready(function() {
$('a').live('click', function () {
var targetUri = $(this).attr('href');
if(targetUri.indexOf(allowedDomain) == -1 && /^https?:\/\/./.test(targetUri)) {
leaving = true;
}
});
});
/* callback for unload event */
function page_unload_or_hidden(evt) {
// test whether the flag shows the users intention about leaving
if (leaving) {
// do this or whatever you want
alert('Where do you go? :-)');
window.open('http://www.codeways.org');
}
}
/* set the callbacks for unload or unload-like events*/
if ('onpagehide' in window) {
// webkit
window.addEventListener('pagehide', page_unload_or_hidden, false);
} else {
// gecko + ie
window.addEventListener('unload', page_unload_or_hidden, false);
}
</script>
</head>
<body>
<div role="main">
<p><a href="http://www.google.de">Google</a></p>
<p><a href="http://www.slashdot.org">Slashdot</a></p>
<p><a href="./exit-notice.html">Stay on site 1</a></p>
<p><a href="/exit-notice.html">Stay on site 2</a></p>
<p><a href="exit-notice.html">Stay on site 3</a></p>
</div>
</body>
</html>
@abits
Copy link

abits commented Jul 14, 2012

Congrats, you are some quick forker :) Two suggestions: I would principally try to isolate the callback for a gui widget from the test for the user's intention. You shouldn't need to touch the "widgets", if you want to modify the test criteria. Also, there should be some kind of globals/settings container object for variables like leaving and allowedDomain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment