Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Please suggest a way to alert user while closing the browser in Mozilla firefox. i have tried the onbeforeunload for IE and Chrome and it does work in both. But I am unable to get the same response in Firefox. It seems that onbeforeunload and onunload is not working in Firefox. Also, in some of the blogs I have found that the onbeforeunload only works with Firefox 4.0 or less version. I have tried the below javascript code and it works for me in IE and Chrome but not in Firefox.


Appreciate, if any alternative is available.

Thanks,
Nishant

What I have tried:

JavaScript
<script language="JavaScript" type="text/javascript">
        var myEvent = window.attachEvent || window.addEventListener;
        var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; 

        myEvent(chkevent, function (e) {
            var confirmationMessage = 'Are you sure to leave the page?';
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
        });

</script>
Posted
Updated 26-Jul-16 2:52am

1 solution

The onbeforeunload event[^] works in all desktop browsers, including the latest version of Firefox.

However, both Chrome (since v51), Firefox (since v44), and Safari (since v9.1) will replace your custom message with a standard message for "security reasons".

The only workaround is to try to hook any events that will result in the user leaving the page, and display your message before the browser handles the event. This can get very complicated, as you need to handle form submission, clicks on <a> elements (but not those that open in a new window, or trigger an in-page action), etc.
 
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