How can I call a server method when the user close

2019-08-12 16:15发布

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

3条回答
女痞
2楼-- · 2019-08-12 16:24

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.

查看更多
beautiful°
3楼-- · 2019-08-12 16:25

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.

查看更多
SAY GOODBYE
4楼-- · 2019-08-12 16:29

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.

查看更多
登录 后发表回答