Abhishek
Abhishek

Reputation: 997

how to kill a application session when a browser window is closed?

i have a problem.

I am working on a chatting application. I want to kill the session if user closes the browser window without logging off. I used 'beforeunload' function but it also fires when a postback event is fired so it's not good for me.

Please help if anyone have any idea about it.

Upvotes: 1

Views: 8062

Answers (5)

Carlos Mora
Carlos Mora

Reputation: 1184

If you have control of sessionID cookie, just set its lifetime to 0, that makes the session die on browser close. The lifetime of the session on the open window can be controled from the server side storing the time last seen in the session and checking

if(isset($_COOKIE[session_name()])) {
    setcookie(session_name(), $_COOKIE[session_name()], 0, "/"); // die @ browser close
}
if(isset($_SESSION['last_time'])){
    if( ( time() - $_SESSION['last_time'] ) > 300 ){ // 5 minutes timeout
        // here kill session;
    }
}
$_SESSION['last_time'] = time();

In the client side you can use the Daniel Melo's answer. I'm using it with one small change:

function endSession() {
   // $.get("<whatever url will end your session>");
   // kill the session id
   document.cookie = 'MYOWNSESSID=; path=/';
}

The only pending matter is that i can't wireup events to input type[buttons] yet, i have made it with raw code, but the all thing works.

Upvotes: 1

Daniel Melo
Daniel Melo

Reputation: 551

As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.

However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).

The script below relies on JQuery

/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;

/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
   $.get("<whatever url will end your session>");
}

function wireUpEvents() {

  /*
  * For a list of events that triggers onbeforeunload on IE
  * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
  */
  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // 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;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
    wireUpEvents();  
});

This script may be included in all pages

<script type="text/javascript" src="js/autoLogoff.js"></script>

Let's go through this code:

  var validNavigation = false;

  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // 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;
  });

A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.

An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.

function endSession() {
   $.get("<whatever url will end your session>");
}

The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session

This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests

PS: I already posted this answer in this question. I am not sure I should answer multiple questions that are similar or post a reference?

Upvotes: 1

Abhishek
Abhishek

Reputation: 997

yup dear, it is okey, but in second thing as you specified that that server didn't receive any response, in my code server only checks the application session and it will find it so it will work. what i want that if the user not log off then the page is killed and after that how can we call any ajax or xmlhttp request from client side to set the application session to offline.

so please guys tell me something this is the only thing is not going well. and thanx for your response.

Upvotes: 1

RameshVel
RameshVel

Reputation: 65877

I suggest you to use the Alexanders approach, but In most cases setting interval time wont alone solve this problem. Because the user may be idle for some time and it may exceed the timeout period.

In order to avoid this, yo need to add one more condition over this.

  • if the user is idle for the timeout period then Just make an AJAX request to server and update the client status as idle.

  • this will avoid logging off the session if the user is idel for certain time.

  • And you can terminate the session if the server didnt recieve any response from client in a specified time and the status is not updated to idle (during browser close or any application hangups).

Upvotes: 1

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

If you use polling to get the chat data, you should kill the session if you don't get a polling request from the client for a given time.

Client:

setInterval (pollData, 10000); /* poll for new data each 10 seconds */

Server:

if (clientX.LastPollTime is over 30 seconds ago) {
    clientX.killSession();
}

Upvotes: 7

Related Questions