1

How to clear session and close the current browser tab on click of log out ?

I am trying to clear session on tab close but not able to find correct way.

1
  • you cannot reliably detect when a user closes a window/tab that's open to your site. you CAN intercept (with JS) when they click a logout button, however. Commented Nov 26, 2013 at 17:18

1 Answer 1

2

You can send an ajax request to to an action method which clears the session variables and in the call back, you can close the window.

<a id=logoutLink">Logout</a>

<script type="text/javascript">

$(function(){

  $("#logoutLink").click(function(e){
   e.preventDefault();
   $.post("@Url.Action("Logout","User")",function(res){
      if(res.status==="done")
      {
         //close the window now.
         window.close();
      }
   });
  });

});
</script>

Now in your UserController, Add the Logout action method

public class UserController : Controller
{
   [HttpPost]
   public ActionResult Logout()
   {
      Session.Abandon();
      return Json(new { status="done"});
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.