Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect the Page Close Event with ASP.NET

I have a ASP.NET web app with a MasterPage and contents page, from the MasterPage when I click a MenuItem to open a new aspx Page. if I want to close the new page browser tab, I want to show a popup or a dialog that alert the user that he is closing the browser tab. I dont know how to detect the close browserTab button. I used the following code in the new aspx page:

<script type="text/javascript">
    function CloseWindow() {
        alert('closing');
        window.close();
    }
</script>

new page code behind:

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}

Thanx in Advantage.

like image 601
H_79 Avatar asked May 16 '13 10:05

H_79


2 Answers

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') ;
    }   
}
like image 90
Aby Avatar answered Sep 28 '22 08:09

Aby


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.

like image 27
Jelle Avatar answered Sep 28 '22 08:09

Jelle