How to Warn Users Before They Attempt to Close a Browser Tab in JavaScript?

To prevent data loss, do you want to create the following warning popup (alert) before a user of your web page attempts to close, reload, or leave the page via the “back” button?

You can do this in a simple step: just copy and paste the following JavaScript code snippet between the <head> ... </head> tags.

<script>
    window.addEventListener('beforeunload', function (e) {
      // Cancel the event
      e.preventDefault();
      // Chrome requires returnValue to be set
      e.returnValue = '';
    });

    window.onbeforeunload=function(){return "Navigating away will lose the changes you've made to your code."};
</script>

By defining the window.onbeforeunload attribute, you tell the browsers (Firefox, Chrome, Internet Explorer, Safari) that there may be some data loss when users close the window.

However, this must be true—you need to have a form, etc. where data actually changed since the user visited the web page. Modern browsers are smart about this feature to prevent missuse.

Leave a Comment