Click here to Skip to main content
15,893,814 members
Articles / Web Development / ASP.NET
Tip/Trick

Session killing (logout) in server when browser is closed using cross button/ALTF4 in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.33/5 (5 votes)
28 Mar 2013CPOL4 min read 56.4K   12   12
The below article helps in executing server side functions when user closes browser abnormally.

Introduction

We might have requirement where we are required to run some server side logic like Session Kills etc when a user closes his browser (using Alt+F4, browser close button, File-Exit click etc). As most of us know IE (or any other browser) does not provide us any way to recognize any client side browser related event (as said above) raised and hence this cannot be achieved from any direct way like catching an event or etc.

This can be handled by some simple workarounds/logics by using some ASP.NET features and some client side coding, Let us see this.

Background

We have some client side events like onBeforeUnload, OnUnload provided to us in JavaScript which are executed whenever a document is unloaded, this may be for a simple Response.Redirect or any other post back raised for executing a server side event (like dropdown selection change or grid view binding events or any event raised from a runat=server control), So we can understand that this event is executed when ever the document is unloaded which includes the browser close also, Hence we can achieve this by just eliminating all the possible unloads from the browser close events. Practically this might be impossible to have a global variable/flag and setting it for all the server side controls client side events, so we are trying to use a generalized approach like write once and use anywhere type of code.

Using the code

ASP.NET provides us many controls which have capability of executing server side events, but in general only two controls <input type='submit'… and <input type='image'… has the ability to submit a form to server, But what ASP does for us is, it automatically creates a client side JavaScript function __doPostBack(eventTarget, eventArgument) and two hidden fields namely __EVENTTARGET and __EVENTARGUMENT. Here for all the controls (other than submit and image) which require a post back, ASP calls this __doPostBack function with the source controls id as the first argument and any required value as the second argument and as seen in the below function here the event raised controls id is stored in the __EVENTTARGET hidden field and the page is submitted manually (you can check this function rendered on any of your webpage source when rendered onto a browser even you are unaware of writing any code like this.

C#
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit ();
    }
}

Hence from the above description we can understand for any post back raised (other than <input type='submit' … and <input type='image') we can confirm that there exists some value (generally controls id) in the __EVENTTARGET hidden field.

We will use the above logic to achieve our requirement, please go through below steps:

  1. Include jQuery library into the aspx page which we are using:
  2. HTML
    <script src="../Js/jquery-1.7.min.js" type="text/javascript"></script>
  3. Declare some Global Variables for distinguishing the different types of post backs.
  4. JavaScript
    var isSubmitPostBack = false;
    var isPostBack = false;var isJSRefresh = false;
  5. Bind a function to document. ready which sets the declared global variables if the page unload is taken place due to submit click or image click or an anchor click (anchor tags does not submit the page but it creates a new GET or POST request to the specified server in the href attribute).
  6. JavaScript
    $(document).ready(function () {
    $("input:submit").click(function () {
    isSubmitPostBack = true;
    });
    $("input:image").click(function () {
    isSubmitPostBack = true;
    });
    $('a:not(a[href^=javascript])').click(function () {
    isSubmitPostBack = true;
    });
    });
  7. Bind a function to window.onUnLoad which checks the reason why the document is unloaded whether it is from __doPostBack or submit or image click or an anchor click. Based on the condition if the unload is not due to any of the above mentioned reasons then open a new window using window. open method (because this opens a new window which carries the same session as the parent window) where in the new page we can handle the events that are required to log out the user.
  8. JavaScript
    window.onunload = function() { LogOut(); }
    function LogOut() {   /*  Checking which event raised the OnUnload.  
        */
            var hdnSrcTarget = $("#__EVENTTARGET")[0];
            if(hdnSrcTarget != null && hdnSrcTarget != 'undefined'){
            if(hdnSrcTarget.value == '')
            isPostBack = false;
            else   
            isPostBack = true;
        }
        var condition = !(isSubmitPostBack || isPostBack || isJSRefresh)
        if((refreshflag != 1 && condition) || logout==true || alterffourflag == 1){
            var logOutWin = window.open("Logout.aspx", "childWindow","width=5,height=5,toolbar=no,<wbr />scrollbars=no,menubar=no"); 
            logOutWin.blur();// Just to blur out the new window so that user does not notice it.
        }
    }

Note: This whole logic can be kept in a Master Page or a Header user control which will be used in all the pages in your web project so that this functionality will be applicable to the whole application.

But here there are some exceptions or some browser side events which can also unload a page like browser refresh or clicking browser back button or changing the URL and hitting Enter. These exceptions can be handled in the new window that is opened. For this follow the below steps:

  1. Create a new web page for handling Session killing events (LogOut.aspx in this case).
  2. Place a button on the page such that it would not be visible on the page.
  3. HTML
    <asp:Button ID="btnLogOut" runat="server" Text="" Style="width: 1px; height: 1px;" />
  4. Call a client side JavaScript function on loading the web page where we get the parent window reference using window. Opener and using this we can check whether the parent window is closed or not, if yes then click the invisible button using JavaScript which raises a server side event that handles all the Session killing logic.
  5. JavaScript
    function CloseWindow(){
    window.opener = self;
    window.close();
    }
    function LogOutSession(){
    var parent = window.opener;
    if(parent){
    if(parent.closed){
    var btn = document.getElementById('<wbr />btnLogOut');
    btn.click();
    }
    else{
    CloseWindow();
    }
    }
    else{
    CloseWindow();
    }
    }

History

  • Created on 22/3/2013.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ADP
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionChrome Issue: window.opener is null Pin
Bhavani Sudha7-Jul-19 22:32
Bhavani Sudha7-Jul-19 22:32 
QuestionIt works.. Pin
Member 122480487-Jan-16 11:28
Member 122480487-Jan-16 11:28 
GeneralMy vote of 1 Pin
Chariklis12-Jun-14 23:32
Chariklis12-Jun-14 23:32 
GeneralMy vote of 2 Pin
Chariklis12-Jun-14 23:28
Chariklis12-Jun-14 23:28 
GeneralRe: My vote of 2 Pin
Karthik Narahari16-Jun-14 20:28
Karthik Narahari16-Jun-14 20:28 
Questionwindow.open Denied by Default Browser's Popup Blockers Pin
friscoch10-May-13 10:23
friscoch10-May-13 10:23 
Thank you for the helpful post. We tried implementing the concept but are facing issues with popups being blocked by default from misc. browsers (FireFox, Chrome, IE, etc). For IE, it works if the site is over http but not https. For the rest, the popup is blocked by default. Is there a workaround, solution without having clients allow those popus for the site explicitly?

Many Thanks
AnswerRe: window.open Denied by Default Browser's Popup Blockers Pin
Karthik Narahari14-May-13 22:22
Karthik Narahari14-May-13 22:22 
GeneralRe: window.open Denied by Default Browser's Popup Blockers Pin
Nelson634020-Jun-17 11:59
Nelson634020-Jun-17 11:59 
QuestionHow to determine the flags? Pin
chengb4-Apr-13 5:34
chengb4-Apr-13 5:34 
AnswerRe: How to determine the flags? Pin
Karthik Narahari14-May-13 21:49
Karthik Narahari14-May-13 21:49 
QuestionInteresting idea, which browsers and versions have you tested this with? Pin
Jason Vogel29-Mar-13 3:29
Jason Vogel29-Mar-13 3:29 
AnswerRe: Interesting idea, which browsers and versions have you tested this with? Pin
Karthik Narahari29-Mar-13 8:38
Karthik Narahari29-Mar-13 8:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.