demo
demo

Reputation: 6235

Check if user leaves page with ASP.NET

I need to clear some Session data that is stored in it if user are redirected to some page.

I found this post where i can see possible solution : https://stackoverflow.com/a/20283726/3917754

But here is one problem - i must enter page Name, according to answer. So entering all page names i don't think is good solution.

Has anybody some ideas how to check if user leaves page to delete session. It must be server side code.

Upvotes: 1

Views: 1750

Answers (1)

Cristina Alboni
Cristina Alboni

Reputation: 1022

You can also do like this:

On each page, define the following script code (or define it in the master page):

   window.onbeforeunload = confirmExit;

            function confirmExit() {
                var url = '<%: ResolveUrl("~/DeleteSessionAjaxHandler.ashx") %>'
                $.ajax({
                    url: url,
                    type: "POST",
                    async: false,
                    data: {},
                    success: function(data) {}
                });
            }

Create the DeleteSessionAjaxHandler.ashx handler and inside delete the session.

public class DeletedSessionAjaxHandler: IHttpHandler, IRequiresSessionState
    {
        public override void ProcessRequest(HttpContext context)
        {
            //Session delete code
        }
    }

Upvotes: 1

Related Questions