Skip to content

Instantly share code, notes, and snippets.

@awinder
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awinder/e9edfdf0e4917276060c to your computer and use it in GitHub Desktop.
Save awinder/e9edfdf0e4917276060c to your computer and use it in GitHub Desktop.

Project Unloader

This is a quick demonstation of the window beforeunload event handler and how you can use it to issue tracking http requests or even use it to prevent a user from closing the window.

<html>
<head>
<link rel="stylesheet" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"
</head>
<body>
<div class="container">
<div class="row">
<h3>This is the page!</h3>
<p>Go to <a href="https://www.runscope.com/stream/0rjrw9c68s3s">https://www.runscope.com/stream/0rjrw9c68s3s</a> to watch the outgoing
HTTP request happen, and then close this page. The request fires through an onBeforeUnload event handler.
Cool stuff! Scary stuff! Interesting stuff?</p>
</div>
<div class="row">
<p>Click here to block the user from leaving by popping up an alert: <input type="checkbox" value="0" /></p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="application/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="application/javascript">
var showAlert = false;
$('input').change(function(value) {
showAlert = !showAlert;
});
$(window).on('beforeunload', function() {
$.post('https://gist-githack-com-0rjrw9c68s3s.runscope.net/', { data: { message: "Leaving user", id: 1 } });
if (showAlert === true) {
return 'Closing the window now will lock this appointment to prevent others from modifying your data.'
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment