1

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.

Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195
Abhishek
  • 957
  • 3
  • 20
  • 43
  • 1
    you can try onunload. but bad idea. it will almost hang the browser when it does the AJAX call. your best bet is to check if the users last activity is greater than say 30-60 seconds and then consider him as offline. – Alec Smart Sep 03 '09 at 06:54

5 Answers5

7

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();
}
Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74
1

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).

RameshVel
  • 64,778
  • 30
  • 169
  • 213
1

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.

Abhishek
  • 957
  • 3
  • 20
  • 43
  • if its a chat application, we have two parties. both can act as a listner and receiver.. both got the same functionlaities. both are pollingg the server for the responses. You cant make AJAX request from a dead browser. But the other party is still online if am right. And he still polls the server. And you can validate if the other user still online or not... whats the problem..?? – RameshVel Sep 03 '09 at 07:41
  • okey, see when a user signin in it i set application(key)="1" for online. now the other side sever checks regularly to application session if the user clicked in log off then it wud be application(key)='0'; and let the user close the window then how i can i change value of this session. – Abhishek Sep 03 '09 at 09:18
  • @Abhisheks.net: Don't add comments as an "Answer". Update/edit your question. – escist Jul 10 '12 at 08:55
1

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?

Community
  • 1
  • 1
Daniel Melo
  • 551
  • 4
  • 9
1

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.

Carlos Mora
  • 1,164
  • 2
  • 12
  • 28