prakashkadakol
prakashkadakol

Reputation: 1237

on unload event of browser

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

<script>

 function onBeforeUnloadAction(){

    return "Would u like to discard Changes";

 }

 window.onbeforeunload = function(){
   if((window.event.clientX<0) ||
      (window.event.clientY<0))
{
     return onBeforeUnloadAction();

   }
 }

 </script>

Upvotes: 2

Views: 1253

Answers (2)

Prutswonder
Prutswonder

Reputation: 10084

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.

Upvotes: 2

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10646

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

Upvotes: 1

Related Questions