Skip to content

Instantly share code, notes, and snippets.

@iMrLopez
Created March 3, 2021 17:10
Show Gist options
  • Save iMrLopez/4dc2d28364cded1fe60b7a294114bd92 to your computer and use it in GitHub Desktop.
Save iMrLopez/4dc2d28364cded1fe60b7a294114bd92 to your computer and use it in GitHub Desktop.
Detect if the browser tab is being closed by the user
<script type="text/javascript">
window.addEventListener('beforeunload', function(e) {
e.preventDefault();
e.returnValue = '';
});
</script>
<b>Detect browser or tab closing</b>
<p>
The beforeunload function is triggered
just before the browser or tab is to be
closed or the page is to be reloaded.
Modern browsers require some interaction
with the page, otherwise the dialog box
is not shown.
</p>
<form>
<textarea placeholder="Trigger an interaction by writing something here"></textarea>
</form>
<!-- CONTACT ME ON: https://github.com/iMrLopez -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment