Skip to content

Detect browser tab close or refresh with JavaScript

You cannot control when user closes or refreshes a web page in a browser tab, but you can let the user know when the tab is closed or refreshed. In this post we will discuss how to detect when a browser tab is closed or refreshed and show an alert.

Advertisements

We can used onbeforeunload event for this purpose. This event is triggered when a user tries to close, refresh the tab or closing the browser itself.

<script type="text/javascript">
 window.onbeforeunload = function () {
  return 'You have unsaved work, it will be lost if you leave this page.';
 }
</script>

If you are working with jQuery..

$(window).bind('beforeunload', function(event) {
	return "You have unsaved work, it will be lost if you leave this page.";
});
See also  The Grid Search - Hackerrank Challenge - Java Solution

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.