Search code examples
javascriptjqueryreloadonbeforeunload

Event beforeunload


i need close the user session with ajax, when this close the nav or tab of my app. For this i'm using the event beforeunload, the issue is when i reload the page with F5(cmr+r, ctrl+r) with this the nav open the warning diag and i don't need this.

$(window).bind('beforeunload',function (e) {
   var message = 'Are you sure you want to leave?';
   return message;
 }

$(window).bind('unload', function () {
  var dataStatus = $('button[name="status"]').attr('data-status');
  if (dataStatus == 'online') {
    var req = $.ajax({
      url: 'mi-url',
      type: 'POST',
      async : true,
      data: {data: JSON.stringify({user_id: <?php echo $user->getId() ?>})},
      dataType: "JSON"
    });
  }
});

Waiting for replys, thanks.


Solution

  • You can't differentiate close tab and tab unload/reload. Instead your old approach, you can set interval 5 minutes or some meaningful time period, and send a notification to the server about session.