Trying to Detect the Browser Close Event

Sharing is caring...

Sometimes you want to detect the browser close event to check whether an user has been submitted the form on a website or not. Or else you need to ask the customers that does he really want to close the browser or accidentally pressed close/back/forward button of a browser. In such cases, the following code will really help you:

window.onbeforeunload = function(event) {
  var message = 'Important: Please click on \'Save\' button to leave this page.';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
};

$(function() {
  $("a").not('#lnkLogOut').click(function() {
    window.onbeforeunload = null;
  });
  $(".btn").click(function() {
    window.onbeforeunload = null;
  });
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements before the browser close.  The WindowEventHandlers.onbeforeunload event handler property contains the code executed when the beforeunload is sent. This event fires when a window is about to unload its resources. The document is still visible and the event is still cancelable. For

browser close prompt

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread. Also, it has been removed from latest version of Google Chrome, Safari and and Opera. In order to get more details about window.beforeunload event handler, read MDN Developer API here.

Originally answered the StackOverflow question here.

Follow me

Ravi Mallya

A Computer geek. Always curious about nature. Eager to learn something new daily. Web Designer/Developer by profession.
Follow me
Sharing is caring...

Ravi Mallya

A Computer geek. Always curious about nature. Eager to learn something new daily. Web Designer/Developer by profession.

Leave a Reply

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