How can end the session when a user closes browser?


can end the session when a use closes browser

1.Session does not end when a user closes browser.
2.There is no communication between the server and client browser is closed.

so there is no way the server can know to end the session.

But we can use the client script to notice the server that we should abandon the session.

Example



Default2.aspx

protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();

}


while calling the default2 page it will end the Session

Default1.aspx

function window.onbeforeunload()
{
if(event.clientX>document.body.clientWidth&&event.clientY<0)
{
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","Default2.aspx",false);
xmlhttp.send();

}
}


Comments

Author: Hitendra18 Mar 2010 Member Level: Gold   Points : 2

You can code against this in the global.asax file like so ...


Sub Session_OnEnd()
Dim conn As New SqlConnection(CONNECT_STRING)
Dim cmd As New SqlCommand( _
"insert into _DummyTbl (Text) values ('GLOBAL')", conn)

conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub


Now if you call the Session.Abandon method the OnEnd event will fire immediately.Now we need some way to call the Session.Abandon method when a user closes their browser. This trick wont work in all web browsers, but you can tap into the onunload() event like so ... TESTA.ASPX


...

When the user closes the browser window at TestA.aspx, they are redirected to TestB.aspx ... TESTB.ASPX


Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Call MyBase.OnLoad(e)

' End The Session
Session.Abandon()

' Build A JavaScript String That Will Close This Web Browser Window
Dim s As String = ""
s &= ""

' Add The JavaScript To The HTML Stream
Page.RegisterClientScriptBlock("close", s)
End Sub


On page load event of TestB.aspx, the code abandons the session then closes the browser immediately. The user never sees this page. In fact to the user, it looks like they closed TestA.aspx.

Author: asdfg18 Mar 2010 Member Level: Gold   Points : 0

in global.asax file
write code for abandoning the session

Author: Happy Coder18 Mar 2010 Member Level: Gold   Points : 1

When you say Closing the browser, it not necessarily need to be clicking the Close button "X".

Will the above be raised when
Browser closed by double clicking on icon top left corner of the window
Browser closed right clicking on taksbar tab and click on close menuitem.

Author: MuhiReks19 Mar 2010 Member Level: Gold   Points : 1

function window.onbeforeunload()
{

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","Default2.aspx",false);
xmlhttp.send();

}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: