Click here to Skip to main content
15,867,964 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Is there any alternative for window.onbeforeunload for Chrome.It working fine in IE but not in chrome,here is my code..


window.onbeforeunload = CloseSession;

function CloseSession() {
//log out the user from demand if browser close or alt+f4 is pressed not for backbutton
if (((window.event.clientY < 0) && (window.event.clientX > 40))
||(event.altKey == true && event.keyCode == 0))
window.open('LogOffUser.aspx', '_parent', 'left = 9999, top = 9999,width=1px, height=1px');
}
Posted
Updated 4-Sep-22 10:08am

1 solution

This is the code that I used to set the onbeforeunload event and it works for Chrome.
The order it was written is crucial though else it wouldnt work.

<script>

    var unloadEvent = function (e) {
        var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";

        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Webkit, Safari, Chrome etc.
    };
    window.addEventListener("beforeunload", unloadEvent);
</script>
 
Share this answer
 
Comments
ShantanuH 7-Jul-14 5:14am    
Instead of showing a Message I want to call another method in that unload event.Its working for the Message but if I write some code in unload event it is not working.
Member 12024996 1-Oct-15 4:26am    
I have looked into this and I now understand why you cannot do anything but show a standardised modal dialog with buttons "Leave this Page" and "Stay on this Page". In the old days, you could close a tab and another one would open and it was difficult to get out of the site you were visiting. Nowadays, you can only choose to leave or stay, as well as do other things. But the other things only happen after you answer that first question, and rightly so, in my opinion, because it means that you can choose to leave the page without it doing anything more, like popping up other tabs or windows.

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