Mehmet Kagan Kayaalp
Mehmet Kagan Kayaalp

Reputation: 565

Logout when the user close the tab

On my Django site, I want to logout from the site automatically when I close the tab or browser. I mean when I close the site by closing the tab instead of using logout button, after entering the URL again, I want to see that the user has already logged out from the site to force the user to enter username and password again.

Is there a way to handle closing the tab in JQuery?

Thank you in advance.

Edit: onunload & onbeforeunload events cause to logout the user when also reloading the page.

Upvotes: 2

Views: 14894

Answers (5)

aravindan
aravindan

Reputation: 11

After a struggle of 3 days I come up with an answer.....

  1. At first set a sessionstorage in login page
sessionStorage.setItem('reloaded', 'yes');
  1. Also set the current URL as previousUrl at sessionStorage in login page itself
sessionStorage.setItem('previousUrl', window.location.href);
  1. After login, once entered into the dashboard
if (sessionStorage.getItem('reloaded') != null) {
  console.log('page was reloaded');
} else {
  console.log('page was not reloaded');
  var previousUrl = sessionStorage.getItem('previousUrl');
  if (previousUrl && previousUrl.endsWith('/login')) {
    console.log('Previous page was login page. Logout not required.');
  } else {
    console.log('logout')
    logout();
  }
}
sessionStorage.setItem('reloaded', 'yes');
sessionStorage.setItem('previousUrl', window.location.href);

function logout() {
  $.ajax({
    url: signOut,
    type: 'POST',
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
    },
    success: function(data) {
      console.log('Logged out successfully');
      window.location.href = loginUrl;
    },
    error: function(xhr, status, error) {
      console.log('Error occurred during logout:', error);
      window.location.href = loginUrl;
    }
  });
}

Explanation:

  1. Check the reloaded is not null to ensure that page was reloaded

  2. Else page was not reloaded. i.e tab gets closed, and opened again, so check the previous URL is login or not

  3. Since tab was closed the previous URL can't be login so logout the user and redirect to login

It works perfectly for my case, hope it will be useful for you guys

Upvotes: 1

PPr
PPr

Reputation: 81

window.onunload = function () { //logout code here... window.open("logout url","log out","height=10,width=10,location=no,menubar=no,status=no,titlebar=no,toolbar=no",true); }

This code works. this will open a small pop up window for the logout url.

Upvotes: 0

Brandon C
Brandon C

Reputation: 81

I just ran into this. In your Django settings.py file, you can add the flag:

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

This will log the user out when the browser is closed. Note that the user will remain logged in if there are other tabs or windows still open (the browser must be completely closed).

Upvotes: 0

Ahmad
Ahmad

Reputation: 1474

Add your logout code to the on onunload event.

window.onunload = function () {
    //logout code here...
}

In JQuery you can use the .unload() function. Remember that you don't have much time so you may send the Ajax request but the result may not reach the client.

Another trick is to open a small new window and handle the logout there.

window.open("logout url","log out","height=10,width=10,location=no,menubar=no,status=no,titlebar=no,toolbar=no",true);

If you want to disable closing the window (or at least warn the user), you can use this code:

window.onbeforeunload = function(event) {
    //if you return anything but null, it will warn the user.
    //optionally you can return a string which most browsers show to the user as the warning message.
    return true;
}

Another trick is to keep pinging the client every few seconds. If no reply comes back, assume the user has closed the window, browser has crashed or there is a network issue that ended the chat session anyway. On the client side, if you don't receive this ping package, you can assume that network connection or server has a problem and you can show the logout warning (and optionally let the user login again).

Upvotes: 1

Kacper Dziubek
Kacper Dziubek

Reputation: 1693

You can use Javascript onunload & onbeforeunload events. In these events destroy the session cookie for Django.

Those events are also fired when you leave a site over a link or your browsers back button so be careful and think twice if this is really what you want.

Upvotes: 0

Related Questions