Search code examples
mailtoonbeforeunload

Prevent onbeforeunload from being called when clicking on mailto link


Is there anyway to prevent onbeforeunload from being called when clicking on mailto link in chrome. In FF, Safari, IE it is working fine.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
        google.load("jquery", "1.3.2");
    </script>

    <script type="text/javascript">
        $(document).ready(function(){
            window.onbeforeunload = confirmExit;
        });

        function confirmExit() {
            return "Are you sure?";
        }
    </script>
</head>
<body>
    <a href="mailto:someone@somewhere.com?subject=test mail&body=Hello%20World">Mail Link</a>
</body>
</html>

Solution

  • What about a workaround?

    $(document).ready(function(){
        mailtoClicked = false;
        window.onbeforeunload = confirmExit;
        //Test if browser is Chrome
        if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
            $('a[href^=mailto]').click(function() {mailtoClicked = true;});
        }
    });
    
    function confirmExit() {
        if (!mailtoClicked) {
            return "Are you sure?";
        } else {
            mailtoClicked = false;
        }
    }
    

    Demo.