0

Possible Duplicate:
How we call logout servlet on browser close event

I want my site to automatically logout user when the browser closes. I use onunload in javascript. Now, my problem is it always logout the user everytime the user navigates to other page. What I want is just to logout when the browser closes.

Here's my code:

<script type="text/javascript">

window.onbeforeunload = confirmExit;
window.onunload = logout;

function confirmExit() {
    return "Are you sure you want to leave?";
}

function logout() {
    window.location = '<?php echo WEBSITE_URL ?>?logout=true';
}

</script>

Hope someone will help me ASAP!

Community
  • 1
  • 1
bayan0926
  • 83
  • 2
  • 12
  • 1
    possible duplicate of [How we call logout servlet on browser close event](http://stackoverflow.com/questions/3986430/how-we-call-logout-servlet-on-browser-close-event) and also of [this](http://stackoverflow.com/questions/12768281/detecting-user-logout-on-browser-close-in-django) and of [this](http://stackoverflow.com/questions/5515416/automatic-log-out-when-browser-closes) and of many others. Please make use of the search facility before asking a question. – Quentin Dec 17 '12 at 09:25
  • https://stackoverflow.com/a/66314375/5729064 – Ihor Khomiak Feb 22 '21 at 11:11

2 Answers2

1

In your case its better to send a ajax request to do the task rather then redirecting the user to logout.

Also send it on onbeforeunload

Or a better idea will be add a cookie with user last activity. and check on every page load the if the last activity is more then the required limit server redirect to the login page clearing the session.

thomaux
  • 19,133
  • 10
  • 76
  • 103
GajendraSinghParihar
  • 9,051
  • 11
  • 36
  • 64
0

I don't think it's possible to detect in javascript when the window is closed. As you've found out onunload event doesn't have the information why the page is unloaded: if the user closes the window or navigates to a different page.

What is more, the user may navigate to a different page by typing the url in the address bar - you might want to 'log him out' in that case too.

The best way to achieve it is to have a timeout on your session. This will work event if the browser crashes.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126