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

Rate this post

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.

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

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

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