Skip to content

Instantly share code, notes, and snippets.

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 coderatchet/a8a8f591a94092fff079d0dcecca513a to your computer and use it in GitHub Desktop.
Save coderatchet/a8a8f591a94092fff079d0dcecca513a to your computer and use it in GitHub Desktop.
goog.events.EventType.BEFOREUNLOAD. Intercepting a tab close using the 'beforeunload' event.
<!doctype html>
<html lang="en">
<head>
<title>BEFOREUNLOAD intercept example</title>
</head>
<body>
<h1>Try to close me!</h1>
<form action="javascript:console.log('stop poking me!');">
<label for="something">sometimes you need to interact with the page before the browser will prompt you.</label><input type="text" id="something" />
<input type="submit" />
</form>
<!--Ensure that the closure-library folder lies in the same directory as this file. -->
<script src="./closure-library/closure/goog/base.js"></script>
<script type="application/javascript" language="JavaScript">
goog.require('goog.dom');
goog.require('goog.events.EventType');
</script>
<script type="application/javascript" language="JavaScript">
console.log('I executed');
var handlerFn = function (event) {
var message = "are you sure you want to leave?";
event.returnValue = message; // this message won't show in most modern browsers. something like "you are
// about to leave, you may lose any unsaved data on this page." will show instead.
return message;
};
window.addEventListener(goog.events.EventType.BEFOREUNLOAD, handlerFn);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment