Skip to content

Instantly share code, notes, and snippets.

@abits
Created July 13, 2012 22:12
Show Gist options
  • Save abits/3107889 to your computer and use it in GitHub Desktop.
Save abits/3107889 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 <chris@codeways.org> -->
<!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 = true;
/* bind all clicks to links to a is_leaving function */
$(document).ready(function() {
$('a').bind('click', is_leaving);
});
/* set flag: true if clicked link is external, false otherwise*/
function is_leaving() {
// do better tests here if necessary
leaving = this.href.indexOf('http://') > -1;
}
/* 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
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</a></p>
</div>
</body>
</html>
@abits
Copy link
Author

abits commented Jul 13, 2012

Do some stuff when user exits site.

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