You have the onUnload event of the body.
!!!!!!! ---> The problem with this event is that you can't cancel the unloading of the page in this event. The event says it itself. onUnload, which means the page is already unloading.
In InternetExplorer, you have the OnBeforeUnload event of the body. This is a good one to check the unloading of a webapp. And you should check google for equal events like onbeforeunload but then for firefox. (for example: google 'onbeforeunload firefox')
There is one this you should keep in mind!!! ---> You can never catch the browser close event for the full 100%.
For example, what if the user kills the browser process. Then the onUnload, or even the onBeforeUnload isn't called.
Oh, here is also some javascript to check if the user clicked the X on the top-right of the browser:
function handleWindowClose()
{
if((window.event.clientX<0) || (window.event.clientY<0))
{
event.returnValue = "If you have made any changes to the fields without clicking the Save button, your changes will be lost.";
}
}
You can for example run this script everytime a mouse button is clicked (well, maybe that's some overhead.) But then again, what if a user closes his browser with the key combination ALT + F4?
Conclusion: Try onbeforeunload as the bodyevent. And use an alternative in case of firefox (search the web). In those events you have to call a javascript function to handle the page-closing.
I hope this info has been usefull.
If you have questions/remarks please do so!
Kind regards,
Wim
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
Hi Nicsam, sorry but I can't give you specific code (because I don't have it), just my considerations ...
Nicsam
now while clicking logout button i have to do some database updation and suddenly
Is it a website/application for an intranet or for the internet? For example when it's for an intranet, you probably know your group of end-users and they can get a training in how to log-out, so that the way of loggin out is consistent. When you have an
internet site you can't do this.
What kind of authentication do you have?
When you press a logout button, then in the click event of that button you will probably do some of these things:
- session.abandon() ----> abandon the user's session
- formsAuthentication.SignOut() ---> if you use forms auth. / this makes the authentication Ticket expire (I guess)
- here you can do your database updates.
!!!!!! BUT as I already said ... what if the user presses ALT + F4 to close the window ....
In the global.asax file you have a Session_End event. Whenever a session expires for a certain user, this event is called. Maybe you can do the database updates here? But there can be a delay on this event. You have to keep that in mind. For example if a
user log's out (the wrong way), and you have set a session timout of 15 minutes, then it can take up to 15 minutes until the event gets called.
I read an article on codeproject once. It was about setting up a session that never expires. Well, it was something like this: He had a very small session timeout, let's say 5 minutes. But then at 4minutes 55seconds, some javascript updated something very
small on the page, which made de sliding expiration of the session timeout go on for another 5 minutes. If the browser is closed then there was no javascript-update possible so the session had a max-timeout of 5 minutes. (I hope you can still follow on this
one) Maybe this is something you can do!, but setting it with a timeout of 1 minute will be too small I guess and may cause overhead for the application.
Nicsam
More over i also need to check if some one try to login with the details which is already logged in.
I searched google on 'asp.net restrict logins' .... and then a few threads on this forum came up, and also some other links ....
In general what they talked about was the following:
- Everytime a user logs in, you should create an Application wide session variable which stores the userName. Then when a user tries to start another session, for example by logging in again from another browser, you can check your app. wide session variable
to see if it exists already. You have to watch out with this approach!!!!!! WHY: This can be a bottleneck for your application depending on where you store your Session information. If it is stored in memory of the WebServer, then it can get overloaded and
your website will hang/crash. Another thing: If the user logs out the wrong way, then the session isn't killed instantly (remember the session timeout). This will cause a lockout for a userAccount for a maximum time equal to the session-timeout.
- You could use a database table where you set flags (boolean) when a user is logged-in. Here you have the same problem as in the above example. You should set the flag back to false again when the user log's out. But because you can't catch the logging-out
of the user with a 100% certainty (well you can with the session_end event I guess), there will be some delay on the database changes and therefore a user can be locked-out for a certain amount of time.
Again sorry that there aren't any specific examples, only considerations.
If you do have questions etc ... let me know!
Kind regards,
Wim
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
Its really answers my doubts, still i need to consider the points you mentioned like the case of (AltF4) and consider all these cases.Definitely I will let you know any doubts with this.
Remember, still as Deblendewim explained. its still not 100%.(eg. user can kill the browser with task manager, or may be can close window from bottom task bar etc..)
Thanks to deblendewim! you explained situation very well.I just have one doubt. does really session_End will execute after perticular session timeout for the user who closed his window? I never tested it, but I just doubt it. lets say in
my Session_End , I am doing something like below.
if (User.Identity.Name.ToString() !=
"")
{
string strUserName = User.Identity.Name.ToString();
// do Rest of database stuff with that UserName (like unlock him/her)
}
will user session who closed his window ever come across this line to execute? I mean User.Identity.Name.ToString() will still available for that user??
I am running into the same issue, I got to know after searching it on goggle for more then 2 hours, that there is no specific way that you can detect the browser closing event, Like Niscam I am having an web app where I need to see if user is ideal for say
30 min or closes browser without log out then I need to update the database values, I am not sure if It is possible but I had seen it live on a web site where it alerts every tieme we try to close browser eben on ALT + F4 and closing the tab from file menu.
Its really shocking for me as I tried the onbeforeunload method which produces alerts every time page is reload or even if i try to navigate away from the page. That takes to search if at the time "onbeforeunload" is called the event is browser close and not
else. I got to knoe the windo.clientX and window.clientY but it only works in IE and not in FF and others.
It entails creating a separate page (in this sample, LogoffPage.aspx) to house the function (the page will never display), but multiple functions to call could be placed there and accessed via the QueryString. This is basically the same as creating a Web
Service, which would be a better solution, but more difficult to post here.
<script type="text/javascript">
<!--
var g_isPostBack = false;
window.onbeforeunload = function ()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogoffPage.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%= Session["UserID"] %>';
var returnCode = callAjax(webUrl, queryString);
//alert(returnCode);
}
// -->
</script>
It really worked for me, I ma feeling like getting a toy from the santa, I had tried this in a test project and its workign fine, I will be implementing this to in my application next week. Thanks Thanks a bunches to you. And yes a, Merry Christmas to
you as well.
Nicsam
Member
293 Points
128 Posts
How to detect the browser close event in ASP.Net (C#)
Sep 03, 2007 07:11 AM|LINK
Hey can any one please brief me on how to detect the browser close event in ASP.Net (C#)
ASP.NET
Nicsam
[!!!!!!!Hopes this helps you!!!!!!!]
deblendewim
Contributor
5590 Points
951 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Sep 03, 2007 10:44 AM|LINK
Hi Nicsam,
You have the onUnload event of the body.
!!!!!!! ---> The problem with this event is that you can't cancel the unloading of the page in this event. The event says it itself. onUnload, which means the page is already unloading.
In InternetExplorer, you have the OnBeforeUnload event of the body. This is a good one to check the unloading of a webapp. And you should check google for equal events like onbeforeunload but then for firefox. (for example: google 'onbeforeunload firefox')
There is one this you should keep in mind!!! ---> You can never catch the browser close event for the full 100%.
For example, what if the user kills the browser process. Then the onUnload, or even the onBeforeUnload isn't called.
Oh, here is also some javascript to check if the user clicked the X on the top-right of the browser:
function handleWindowClose() { if((window.event.clientX<0) || (window.event.clientY<0)) { event.returnValue = "If you have made any changes to the fields without clicking the Save button, your changes will be lost."; } }You can for example run this script everytime a mouse button is clicked (well, maybe that's some overhead.) But then again, what if a user closes his browser with the key combination ALT + F4?
Conclusion: Try onbeforeunload as the bodyevent. And use an alternative in case of firefox (search the web). In those events you have to call a javascript function to handle the page-closing.
I hope this info has been usefull.
If you have questions/remarks please do so!
Kind regards,
Wim
Nicsam
Member
293 Points
128 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Sep 04, 2007 07:13 AM|LINK
Hi Wim Thanks for your comments. Its absolutely answer my question.
Its really a worthy answer.
Actually i have a requirement like for example I have a login page and i have logged in,
now while clicking logout button i have to do some database updation and suddenly without clicking the logout button if the user
closes the window no updation will take place. More over i also need to check if some one try to login with the details which is already logged in.
Can you please comment on this
Regards Nicsam
asp.NET
Nicsam
[!!!!!!!Hopes this helps you!!!!!!!]
deblendewim
Contributor
5590 Points
951 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Sep 04, 2007 11:06 AM|LINK
Hi Nicsam, sorry but I can't give you specific code (because I don't have it), just my considerations ...
Is it a website/application for an intranet or for the internet? For example when it's for an intranet, you probably know your group of end-users and they can get a training in how to log-out, so that the way of loggin out is consistent. When you have an internet site you can't do this.
What kind of authentication do you have?
When you press a logout button, then in the click event of that button you will probably do some of these things:
- session.abandon() ----> abandon the user's session
- formsAuthentication.SignOut() ---> if you use forms auth. / this makes the authentication Ticket expire (I guess)
- here you can do your database updates.
!!!!!! BUT as I already said ... what if the user presses ALT + F4 to close the window ....
In the global.asax file you have a Session_End event. Whenever a session expires for a certain user, this event is called. Maybe you can do the database updates here? But there can be a delay on this event. You have to keep that in mind. For example if a user log's out (the wrong way), and you have set a session timout of 15 minutes, then it can take up to 15 minutes until the event gets called.
I read an article on codeproject once. It was about setting up a session that never expires. Well, it was something like this: He had a very small session timeout, let's say 5 minutes. But then at 4minutes 55seconds, some javascript updated something very small on the page, which made de sliding expiration of the session timeout go on for another 5 minutes. If the browser is closed then there was no javascript-update possible so the session had a max-timeout of 5 minutes. (I hope you can still follow on this one) Maybe this is something you can do!, but setting it with a timeout of 1 minute will be too small I guess and may cause overhead for the application.
I searched google on 'asp.net restrict logins' .... and then a few threads on this forum came up, and also some other links ....
In general what they talked about was the following:
- Everytime a user logs in, you should create an Application wide session variable which stores the userName. Then when a user tries to start another session, for example by logging in again from another browser, you can check your app. wide session variable to see if it exists already. You have to watch out with this approach!!!!!! WHY: This can be a bottleneck for your application depending on where you store your Session information. If it is stored in memory of the WebServer, then it can get overloaded and your website will hang/crash. Another thing: If the user logs out the wrong way, then the session isn't killed instantly (remember the session timeout). This will cause a lockout for a userAccount for a maximum time equal to the session-timeout.
- You could use a database table where you set flags (boolean) when a user is logged-in. Here you have the same problem as in the above example. You should set the flag back to false again when the user log's out. But because you can't catch the logging-out of the user with a 100% certainty (well you can with the session_end event I guess), there will be some delay on the database changes and therefore a user can be locked-out for a certain amount of time.
Again sorry that there aren't any specific examples, only considerations.
If you do have questions etc ... let me know!
Kind regards,
Wim
Nicsam
Member
293 Points
128 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Sep 06, 2007 11:29 AM|LINK
Hi Wim Thanks for your comments.
Its really answers my doubts, still i need to consider the points you mentioned like the case of (AltF4) and consider all these cases.Definitely I will let you know any doubts with this.
Thanks
Nicsam
[!!!!!!!Hopes this helps you!!!!!!!]
BhaveshPatel
Member
353 Points
128 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Mar 08, 2008 04:02 PM|LINK
Here is solution for ALT+F4,
if (event.altKey==true && event.keyCode==0 ){ alert(
"ALT + F4 being pressed"); }Remember, still as Deblendewim explained. its still not 100%.(eg. user can kill the browser with task manager, or may be can close window from bottom task bar etc..)
Thanks to deblendewim! you explained situation very well.I just have one doubt. does really session_End will execute after perticular session timeout for the user who closed his window? I never tested it, but I just doubt it. lets say in my Session_End , I am doing something like below.
if (User.Identity.Name.ToString() != ""){
string strUserName = User.Identity.Name.ToString(); // do Rest of database stuff with that UserName (like unlock him/her)}
will user session who closed his window ever come across this line to execute? I mean User.Identity.Name.ToString() will still available for that user??
Bhavesh Patel
NiravVyas
Participant
912 Points
217 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Dec 24, 2009 04:21 PM|LINK
Hey Guys,
I am running into the same issue, I got to know after searching it on goggle for more then 2 hours, that there is no specific way that you can detect the browser closing event, Like Niscam I am having an web app where I need to see if user is ideal for say 30 min or closes browser without log out then I need to update the database values, I am not sure if It is possible but I had seen it live on a web site where it alerts every tieme we try to close browser eben on ALT + F4 and closing the tab from file menu. Its really shocking for me as I tried the onbeforeunload method which produces alerts every time page is reload or even if i try to navigate away from the page. That takes to search if at the time "onbeforeunload" is called the event is browser close and not else. I got to knoe the windo.clientX and window.clientY but it only works in IE and not in FF and others.
Please do reply if any ideas...
Thanks
Thanks
Nirav
NC01
All-Star
82577 Points
15430 Posts
MVP
Re: How to detect the browser close event in ASP.Net (C#)
Dec 24, 2009 04:36 PM|LINK
Here is a sample of calling a server-side method when a window is closed. The server-side functionality is written in C#, but is easily converted to VB by using http://authors.aspalliance.com/aldotnet/examples/translate.aspx
It entails creating a separate page (in this sample, LogoffPage.aspx) to house the function (the page will never display), but multiple functions to call could be placed there and accessed via the QueryString. This is basically the same as creating a Web Service, which would be a better solution, but more difficult to post here.
//////////////////////////////////////////////////////////////////////////
// Page1.aspx
//////////////////////////////////////////////////////////////////////////
<script type="text/javascript">
<!--
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
// -->
</script>
<script type="text/javascript">
<!--
var g_isPostBack = false;
window.onbeforeunload = function ()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogoffPage.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%= Session["UserID"] %>';
var returnCode = callAjax(webUrl, queryString);
//alert(returnCode);
}
// -->
</script>
//////////////////////////////////////////////////////////////////////////
// Page1.aspx.cs
//////////////////////////////////////////////////////////////////////////
private void Page_Load(object sender, System.EventArgs e)
{
if ( this.IsPostBack )
{
this.Session["UserID"] = "12345";
}
this.RegisterOnSubmitStatement("OnSubmitScript", "g_isPostBack = true;");
}
//////////////////////////////////////////////////////////////////////////
// LogoffPage.aspx.cs
//////////////////////////////////////////////////////////////////////////
protected string LogoffUser(string userId)
{
string returnValue = "OK";
// Call the database, logging the user off here...
return returnValue;
}
private void Page_Load(object sender, System.EventArgs e)
{
string logoffDatabase = (this.Request["LogoffDatabase"] == null) ? string.Empty : this.Request["LogoffDatabase"];
string returnValue = string.Empty;
if ( logoffDatabase == "Y" )
{
if ( returnValue.Length > 0 )
returnValue += ", ";
returnValue += this.LogoffUser(this.Session["UserID"].ToString());
}
this.Response.ClearHeaders();
this.Response.Clear();
this.Response.Write(returnValue);
this.Response.End();
}
NC...
NiravVyas
Participant
912 Points
217 Posts
Re: How to detect the browser close event in ASP.Net (C#)
Dec 26, 2009 12:13 PM|LINK
Hi,
It really worked for me, I ma feeling like getting a toy from the santa, I had tried this in a test project and its workign fine, I will be implementing this to in my application next week. Thanks Thanks a bunches to you. And yes a, Merry Christmas to you as well.
Thanks
Thanks
Nirav
vid_s21
Member
2 Points
1 Post
Re: How to detect the browser close event in ASP.Net (C#)
Apr 05, 2010 05:55 AM|LINK
Hi,
I needed a similar solution and I tried implementing this method in my c# asp.net application. Its not working.
I need to change a value in database , if the user closes the browser without logging off. Please let me know why its not working.
Regards,
vidya