detect-browser-close-event-and-alert-some-messages-using-javascript/

Last updated on February 9th, 2022 at 10:45 am

Javascript Detect browser close event and alert message

This script will help you to detect browser or tab close event and alert some messages. Even this script will be useful to call some Ajax functions which terminate connection to Database or something related.

Tested on latest version of Chrome and Internet Explorer 11.0 and Microsoft Edge. [Last validated on Sept 24th 2016]

Tested on latest version of Chrome, Firefox, Safari [Last validated on Feb 9th 2022]

If you would like to run some functions before closing the browser, check this tutorial on Calling a function before leaving a website using Javascript.

You can try this code, it basically calls onbeforeunload property of the WindowEventHandlers

<body onbeforeunload="return check()">
<script type="text/javascript">
window.onbeforeunload = check;
function check()
{
return "Are you sure you want to exit this page?";
//or put whatever function you need to call when a user closes the web //browser.
}
</script>
<body>
Body of the page goes here.
</body>

Demo

Note: In the demo you must type something in the input field or click somewhere in the page to activate the listener. Simply opening the demo page and closing it may not trigger a confirmation pop up

24 thoughts on “Javascript Detect browser close event alert message”
        1. Hi Prasenjit, Thanks for the comment.
          For that you need to add after the alert command something like

          newWindow=window.open('logout.php','','width=450,height=350')
          newWindow.focus();
          

          Where logout.php is your logout script.Hope your script works as expected.

            1. Remove all the existing functions for unload event and add this, it will work on all browsers like Firfox, Chrome and IE.

              window.onbeforeunload = function (my_event) {
              var message = "Your logout page has been opened in a new window, Check that out. Make sure that you have enabled pop up in your browser to see that?";
              if (typeof my_event == 'undefined') {
              my_event = window.event;
              }
              if (my_event) {
              newWindow=window.open('test.html','','width=450,height=350')
              newWindow.document.write("<p>This is 'newWindow'</p>")
              newWindow.focus();
              my_event.returnValue = message;
              }
              return message;
              }
              
    1. Hii

      It is working in all the cases in window load and close I want want it only in close case what should I do plz suggest 🙂

  1. is there a way that it will delete my session in the database?

    like this (no working example)

    window.onbeforeunload = function (my_event) {
    if (typeof my_event == ‘undefined’) {
    my_event = window.event;
    }
    if (my_event) {
    newWindow=window.open(‘http://www.url.com/logout.php?sesjion=’)
    newWindow.focus();
    my_event.returnValue = alert;
    }
    return alert;
    }

    }

    thanks in advance.

    kindest regards Menno

    1. if (my_event) {
      newWindow=window.open(‘http://www.url.com/logout.php?sesjion= php string session end php’)
      newWindow.focus();
      my_event.returnValue = message;

      the link will be:
      http://www.url.com/logout.php?sesjion=e4b9f06fe57c6e9b98b60e4463525092

      it needs to take the session to the logout.php page in the URL bar.
      then destroy it.

      Logged in member –> closes browser –> open the page
      http://www.url.com/logout.php?sesjion=e4b9f06fe57c6e9b98b60e4463525092
      session_destroy
      update DB set session to ’empty’.

      on manual this works 🙂 now i need the script to do it.

      Thanks in advance
      Menno

      1. Please check my previous comment. Replace the URL in that with anything according to your requirement. Add a auto close window script which will close that window automatically once the logout session is empty.

    2. Hi Menno,

      Thank you very much for your query. Yes there is a way to do that. As mentioned in the script inside the myUnloadEvent() function you can add your URL that will delete the session from your db, You can do a simple approach like this.

      function myUnloadEvent() {
          alert ('Calling some alert messages here');
          //even you can call some functions that will terminater the DB connections or something similar.
      newWindow=window.open(‘http://www.url.com/logout.php?sesjion=’)
      newWindow.focus();
      }
      

      Else use the script you have pasted. If that doesn’t work go ahead with mine 🙂

      Regards
      Admin[Mistonline.in]

  2. Hello,

    the script is great!
    But unfortunately when we are on a web application including main_menu frame, each time we go from one menu to another we get the alert, or even when we click on a link.

    Is there any way to only detect browser closing and not unload?

    Thanks.
    Manickam

  3. Its possible in chrome detect when browser or tab closed but NOT showing a message, directly open a popup, I dont wanna show a message, it is possible?

  4. I dont want the message to be given to user if the browser gets refreshed..i need a notification only when the user clicks on (X) to close the browser..please help

    1. Hi Vikas,

      For that you can use Cookies. If you can wait for some more time my next post will be based on that 🙂

      Regards
      Admin

  5. Sir, I want to set my database value from 1 to 0 when browser is closed….Is there any way to do this..please assist me..Thank you

    1. You can use jquery for that. Javascript has onbeforeunload() but at times it will not be compatible with some browser.

      Jquery code should looks something like this

      $(window).unload( function () {
            $.ajax({
              url: YourWebsiteURL,
              type: "GET",
              data: "var1=POST_VALUE",
              cache: true,
              success: function(response){
      
              }
              });
          } );
      

      Hope this will give you some hint on how to do it 🙂

  6. HI Thanks,

    The script you all mentioned above is working but onbeforeunload event is being fired on browser close as well as on page refresh. Is there any way to fire this event only on browser close not on page refresh. For F4 and CTRL+F4 we can trace key code and prevent them but what to do in case of browser refresh button click or if someonel click in address bar and press enter. In these cases your script is not working. I would appreciate any help in it. Looking forward to hear you you.

    var validNavigation = false;
    var test=false;

    function wireUpEvents() {

    var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
    var leave_message = ‘You sure you want to leave?’
    function goodbye(e) {
    if (!validNavigation) {
    if (dont_confirm_leave!==1) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE – this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = leave_message;
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
    e.stopPropagation();
    e.preventDefault();
    }
    //return works for Chrome and Safari
    return leave_message;
    }
    }
    }

    window.onbeforeunload= (function(event){

    if(!validNavigation){
    return goodbye(event);
    }
    })
    // Attach the event keypress to exclude the F5 refresh
    $(document).bind(‘keydown’, function(e) {
    getKeyCode(e);

    if (keyCd == 116){
    validNavigation = true;
    }

    if (altKy && (keyCd == 18 || keyCd == 115)) {
    validNavigation = true;
    }
    if (keyCd == 13) {
    validNavigation = true;
    }
    });

    // Attach the event click for all links in the page
    $(“a”).bind(“click”, function() {
    validNavigation = true;
    });

    // Attach the event submit for all forms in the page
    $(“form”).bind(“submit”, function() {
    validNavigation = true;
    });

    // Attach the event click for all inputs in the page
    $(“input[type=submit]”).bind(“click”, function() {
    validNavigation = true;
    });

    }

    function getMouseButton(event) {
    if (IE == true) {
    mouseBtn = event.button;
    }
    if (Netscape == true) {
    if (event.which == null)
    mouseBtn = event.button;
    else
    mouseBtn = event.which;

    }
    }
    function getKeyCode(event) {
    if (IE == true) {
    keyCd = event.keyCode;
    altKy = event.altKey;
    ctlKy = event.ctlKey;
    shiftKy = event.shiftKey;
    }
    if (Netscape == true) {
    if (event.which == null)
    keyCd = event.keyCode;
    else
    keyCd = event.which;

    altKy = event.altKey;
    ctlKy = event.ctrlKey;
    shiftKy = event.shiftKey;
    }

    }
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
    var keyCd, altKy, mouseBtn, ctlKy, shiftKy;
    Browser = navigator.appName
    Net = Browser.indexOf(“Netscape”)
    Micro = Browser.indexOf(“Microsoft”)
    Netscape = false
    IE = false
    if (Net >= 0) {
    window.captureEvents(Event.MOUSEDOWN)

    Netscape = true
    }
    if (Micro >= 0) {
    IE = true
    }
    wireUpEvents();

    });

    1. Hello Rakesh, Thanks a lot for your comment.

      Please refer http://www.w3schools.com/tags/ref_eventattributes.asp, and kindly note that only window object has a load event. So as far as i know you will not be able to trigger a function only when you refresh your webpage.

      The script i have given below is the closest one i can recommend for you. This will work when you close, refresh or type a new address and click enter on the address bar.

      window.onbeforeunload = function() {
          return "Are you sure you want to navigate away?";
      }
      

Leave a Reply

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