How to execute a Method when a User close the Browser or visit another Page?
I use c# asp.net 4 web.forms.
I have a page (lets called it X) I need execute a method on X in this situation only:
- When User visit another URL, directly input in the Browser or clicking another link on the Page.
- When User Log Out from my Web Application.
- When a User Close the Browser.
At the moment I'm trying Page_Unload Event
but as for MSDN "Occurs when the server control is un开发者_高级运维loaded from memory" and I'm not able to make it works as expected.
Looking in the documentation I cannot find a suitable Event for my Page.
What are the possible alternative solutions? Thanks for your time on this.
This simply isn't possible.
HTTP requires browsers to request resources from the server first - without this the server cannot do anything. Closing your browser will not request anything from the server.
Your only option is to use session cookies, which are wiped when the user ends the browsers session, as per MSDN:
When the user closes the browser, the cookie is discarded.
So checking for these on each request will allow the server to know if the user has previously closed the browser.
There are nasty javascript solutions, but these are very much hacks.
Have a look at the javascript window.OnBeforeUnload handler :
How can I override the OnBeforeUnload dialog and replace it with my own?
This way you can execute some javascript before the user leaves your page.
When User visit another URL, directly input in the Browser or clicking another link on the Page
you can do some client side scripting. javascript onbeforeunload Event might help you.
When User Log Out from my Web Application.
don't see why this is a problem. this sure is a server side event, isn't it?
When a User Close the Browser
that's a problem. what should happen in a case of power failure? or browser crash? or...
精彩评论