Geek
Geek

Reputation: 3329

How to handle browser close event through Java script

I have an application which logs users session once he logins. Say I have view case page and when user clicks a case it would be locked by that user and the action is tracked by inserting an entry into lock table with the java Session, caseid and userId.

Now when the user click any other tab within the application, including logout an action is called to delete the session id in the lock table for that user and case. I have a requirement to release this lock even when the user closes the browser close button. My backend code will handle the scenario when the elapsedTime of the lock is greater than 10mins.

However, when the user closes the browser and some other user logins to view the same case within this span of 10mins it still shows the lock by the previous user. So I have to capture the browser close event and do the same action as I do for logout and other tab click.

My below piece of java script code works well in IE browser for browser close but doesn't work in chrome or firefox. Can someone suggest which event to use in chrome/firefox please?

<script type="text/javascript">
    document.getElementById('logoff').onclick = function() {
        sessionStorage.setItem('accept', '0');
        location.href="/abc/logout/";
    };
    $(document).ready(function() {         
    
    var validNavigation = false;
    
    // Attach the event keypress to exclude the F5 refresh (includes normal refresh)
    $(document).bind('keypress', function(e) {
        if (e.keyCode == 116) {
            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;
    }); 
    
    $("input[type=button]").bind("click", function() {
      validNavigation = true;
    }); 
    
    window.onbeforeunload = function() { 
    if (!validNavigation) {     
            sessionStorage.setItem('accept', '0');
            location.href="/abc/logout/";
        }
    };
    
    });
    
</script>

Upvotes: 0

Views: 204

Answers (1)

Gh05d
Gh05d

Reputation: 8962

It seems like using the onbeforeunload property is discouraged:

Typically, it is better to use window.addEventListener() and the beforeunload event, instead of onbeforeunload.

It should look like this:

window.addEventListener('beforeunload', function (e) {
  // the absence of a returnValue property on the event will guarantee the browser unload happens
  delete e['returnValue'];
  if (!validNavigation) {     
    sessionStorage.setItem('accept', '0');
    location.href="/abc/logout/";
  }
});

Upvotes: 1

Related Questions