how to detect the Page Close Event with ASP.NET

拥有回忆 提交于 2019-11-30 20:07:04
Aby

This works perfect.

javascript detect browser close tab/close browser

<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}

I had a lot of problems with this myself and the only thing that works is: "window.onbeforeunload" event from javascripts but the problem is this gets executed a lot more than when you'd expect. So basicly if your working with a master page etc I don't think it can be done.

I think it's best you try to approach this differently because else your closing message will show up to often.

You can handle this with javascript in your page.
First create a function:

function closeMessage() {
    return "Are you sure you want to leave this page";
}

After that assign this method:

window.onbeforeunload = closeMessage;

Please let me know if was helpfull

You need to catch the event for closing the browser and use it to do whatever you wanna do. Here is the code that worked for me.

        <script type="text/javascript">
          window.onbeforeunload = function (e) {
               var e = e || window.event;
               if (e) e.returnValue = 'Browser is being closed, is it okay?';//for IE & Firefox
               return 'Browser is being closed, is it okay?';// for Safari and Chrome
           };
        </script>

Hope this helps..

Dinesh Haraveer

If I get you correctly, you want to know when a tab/window is effectively closed. Well, afaik your only way in Javascript to detect that kind of stuff are onunload & onbeforeunload events. Those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.you can go through browser-tab-close-detection-using-javascript-or-any-other-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!