on unload event of browser

前端 未结 2 1317
不知归路
不知归路 2021-01-15 11:31

HI

I wanna timeout session from client page,i tried below code but not able to execute code need some help of how i can handle OK or CANCEL events from user

相关标签:
2条回答
  • 2021-01-15 12:08

    onbeforeunload must return a string, the browser creates the confirm box from that string. If you want to capture that the user didn't leave (You cannot run anything if the user left, thats just how it is), simply set a timer and see if it fires:

    window.onbeforeunload = function(){
        setTimeout(function(){
            //User didnt leave
            goDoFunStuff();
        },500);
        return 'wanna go?'
    }
    

    Since onbeforeunload is blocking the timer will only fire if the user didnt leave

    0 讨论(0)
  • 2021-01-15 12:10

    The beforeunload event can only be used to display a dialog to the user that he/she is about to navigate away from the current page. This dialog is browser-controlled and you can only customize the dialog's warning, not it's outcome. Therefore, you cannot execute an action based on the outcome of the dialog. This is mainly for security reasons, to prevent people from being forced to stay on the current page.

    If you want to cleanup any session data after the person leaves the current page, you should consider using one (or several) of these alternative constructions:

    1. Inplement your own 'back' or 'cancel' button on your page, which you can handle to display your own dialog and perform the cleanup.
    2. Log server requests per session and perform a cleanup on those sessions that haven't made any request in a specific interval.
    3. Perform a daily cleanup of old sessions, preferably at a low visiting time.
    0 讨论(0)
提交回复
热议问题