Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When I close the browser window by pressing the "X" button in the top right corner, I need to call my logout.aspx page. I need a solution that works in all browsers and should work only when the "X" button in the top right corner of the browser window is pressed . Tried everything with onbeforeunload , but nothing seems to work in chrome. Any sample code would be greatly appreciated


What I have tried:

!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
            function test() {            
                window.open('https://forums.asp.net/t/2161554.aspx')
            }
        </script>

</head>
<body onbeforeunload="test();">
    <form id="form1" runat="server">
        <div>          
        </div>
    </form>
</body>
</html>
Posted
Updated 12-Dec-22 23:08pm

1 solution

I don't think there's any way to guarantee that a request like that will be made. When a user closes a browser window/tab they're terminating the process that's running for that page, so the process won't be able to execute any more requests. The closest you can get is using the onunload and onbeforeunload events which, again, won't fire because the browser window/tab has been closed.

If you need a session to persist until a browser window/tab is closed then make sure that the associated session cookie does not have an expiration time. The default behaviour on browsers is that a cookie without any expiration time will be removed once the window/tab is closed.

If you need this page to be called due to some additional processing (ie. writing audit records or doing server-side clean-up) you'd have to come up with an alternate solution. For example, you could keep track of when users were last active in the application (ie. when they last accessed any screen) and after a set period of time, call your processing/clean-up code. This isn't perfect though as this could trigger if a user ends up spending some time on something else.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900