Monday, 29 August 2011

Warn user before closing browser window OR catch browser close event

Is there a way to catch the browser close event? No.. No..a big No
        But we can do some workaround to achieve this functionality, I cannot say it is a straight forward solution but it is the only way of doing it. Since there is no way you can catch a browser close event, here i am demonstrating how we can use the onbeforeunload event which will fire before every document unload. So here document unload can be anything like close, refresh, redirect, submit...etc.

    In my example I have created a JavaScript global variable called xCheck and initialize to 'Y'.
var xCheck;
xCheck = 'Y';

Create a JavaScript function called windowClose which checks the flag and returns a message string
function windowClose()
{
  if(xCheck=='Y')
   {
    return "Are you sure you want to logout from this app?";
   }
}

Now assign the window onbeforeunload to the above JavaScript function
if ( $v('pFlowStepId')!='101' )
{
 window.onbeforeunload = windowClose;
}

But this will fire the windowClose function each time the document is unloaded which will be annoying. So it is easy to exclude all submits, redirects, JavaScript functions, anchors...etc
$(document).ready(function() {
   $("[href]").click(function () {
       xCheck='N';
    });
   $(":button").click(function () {
       xCheck='N';
    });
   $(document).click(function () {
       xCheck='N';
    });
   $(document).mouseover(function () {
       xCheck='Y';
    });
 });

No comments:

Post a Comment