breaking into the unknown…

clear session or cookie on browser close

Leave a comment

The session and cookie automatically get cleared when a user logout. But there is possibility that user close the browser without loging out . So for security reasons here, you want to clear all session data when user close the Browser . I will explian it in terms of ruby, but the basic flow remain same for any language.

STEP 1 : catch the browser close event.

I am using jQuery, but find that unload function is not working for me .The browser get closed without firing my alert. After googling for some time I find the alternative in onbeforeunload .

<script type=”text/javascript”>

window.onbeforeunload = function (){

alert(“I will do cleanup here”)

return “any string or keep it empty string”



so, the alert appear before the browser get closed, showing that the callback is getting fired. We will write our clean up code in its place. The return statement will trigger popup asking the user to leave the page or stay on the page. If you do not want this behaviour don’t use the return statement.

keep the script on the page you want to do cleanup, when user close the browser. If you want it for all the pages put it in your common Layout page.

STEP 2 : make a ajax call to your controller which will clear the session

<script type=”text/javascript”>

window.onbeforeunload = function (){


url: “<%=session_clear_url%>”,

type: “POST”,

data: {},

contentType: “application/json; charset=utf-8”,

dataType: “json”




The URL should be of your action where you clear the session. In my case the path session_clear_url is actually a ruby syntax it is defined in Routes as below:

match 'clearSession' => 'loans#session_clear', :as => :session_clear

So,  It will go to session_clear action of the loan controller.

STEP 3: writing the cleanup code in the controller action

  def session_clear
    session[:EsignDisclosureAccepted] = nil
    session[:AccountNo] = nil
    render :text => "session cleared"

So you can see that I have set EsignDisclosureAccepted and AccountNo data in session to null, which is equivalent to deleting it. You can do any other cleanup here as provided by language you are using.

Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s