How can I call a server method when the user close the page
I want to remove a temp file from the server after the user close the page (I assumed I don't have this callback on the server by default),
I tried to call a server side method using (ICallbackEventHandler
implementation) when the user close the page, but the problem is that the server side method doesn't fire in this case (closing the page), it only response if the page still opened. and I don't prefer to stop closing the page until the server response and send its call back to close the page manually.
In case I must stop closing the page开发者_如何转开发, kindly help me with the best way.
Thanks in advance
You can't really know when user is closing the page.
Best you can achieve is using the JS onunload
event and in there send AJAX request:
<body onunload="SendRequest();">
And the JavaScript: (jQuery is most simple way)
function SendRequest()
{
var sURL = "http://localhost/Log.aspx?action=unload&t=" + (new Date()).getTime();
$.ajax({ url: sURL });
}
This event will be triggered whenever user navigates away from the page: F5, Back, Forward, clicking a link, submitting a form etc... you can improve the code to ignore cases like clicking something in the page let me know if relevant and I'll edit with proper code.
I think it might just be more prudent to delete the file after some time period, say 24 hours, on a recently-accessed basis. That is, all files who haven't been touched in 24 hours get deleted.
Alternatively, you could poll with AJAX, and as soon as you don't receive a request with the user's identifying token within some time threshhold > the polling interval, delete the relevant file.
In a similar situation in my first job, I left the copy on the server and whenever that temp directory was called again from that page, I deleted any files older than 72 hours. Not very good, but was accepted in that situation.
If you need to delete it on the server when you know the user doesn't require it any more, you could use a session listener, see this question.
精彩评论