In an extranet or intranet website you may want to limit the user’s access to a unique machine at at time.
One way to do that is to have a table with the logged users and check the new user against that table and block his access if there is already one instance of that user logged in.
But, what if the user shutdown the browser, or the computer, without logging out of the system ? In that case, he will never be able to loggin again, unless he calls support to clear his record or waits until the session time out.

I found a way to clear the user records in case of window or browser closing, but your content should be inside an iFrame, to keep the main window open and the user logged in. When the user changes pages or close the browser, the event “onBeforeUnload” will call a javascript function that calls a CF template to kill the user session. In that template that kills the session, you may write your code to update the user table.

Download the sample code here.

I wrote a small test environmet to show this action. Start testing by calling the template: killSectionTest.cfm. It will show a login form and the intranet frame.
Once you submit the form, it will call itself and will show the session data instead of the login form.
In parallel, open another window or tab and call the template killSessionCheck.cfm.
It will show a dump of the session scope, and you will see the variables “userID” and “userName”, as well as the variable “loggedIn” with the value “true”.
Now, in the previous intranet window, you may navigate inside the intranet frame (next, previous).
When you change the page or close that window, refresh the window killSessionCheck.cfm and you will see that the variables “userID” and “userName” disappeared and the variable “loggedIn” now has the value “false”.
Here is the javascript function:<script language="JavaScript">
function killSession(){
var settings = "width=1,height=1,resizable=no";
var win ="http://localhost/testsite/killSession.cfm","win",settings);

Here is the body tag:<body onBeforeUnload="killSession();">

3 thoughts on “Kill Session When User Closes the Browser

  1. I would like to point out this method will not work in the event of a browser/OS crash, power failure, or loss of network connectivity.

    It is, however, the closest you can probably get without having every page in the site “phone home” every so many seconds.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.