0

What is the best way for page closed event detection ?

I have a page and I want to check if the page get's closed. I have to do something if the user closes the page.

I tried this way and it didn't work.

I will rollback progress if user leave.

MercyDude
  • 884
  • 10
  • 27
serdar
  • 454
  • 1
  • 8
  • 26

2 Answers2

0
  1. Write the code in project.

    C#:

    using System.Web.Services;
    
    [WebMethod]
    public static void AbandonSession()
    {
      HttpContext.Current.Session.Abandon();
    }
    

    VB.NET:

    Imports System.Web.Services
    
    <WebMethod> _
    Public Shared Sub AbandonSession()
      HttpContext.Current.Session.Abandon()
    End Sub
    
  2. Add a script tag in between head tag of Default.aspx page and write following code:

    <script type="text/javascript">
      function HandleOnclose() {
        alert("Close Session");
        PageMethods.AbandonSession();
      }
      window.onbeforeunload = HandleOnclose;
    </script>
    

    Edit the function to serve your purpose and you should be fine.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Dre Ross
  • 1,236
  • 1
  • 8
  • 9
0

you can use beforeunload in javascript, check this example

<script type="text/javascript">
$(document).ready(function () {
    $(window).on('beforeunload', function () {
        return 'Do something...';
    });
});