javascriptjqueryzepto

$(window).on doesn't work as expected when migrating from jquery to zepto


Previously, I have a JavaScript code, which will pop up a dialog & perform redirection when user closes the browser.

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
    $(document).ready(function() {
        var url     = 'http://www.yahoo.com';
        var message = 'go to yahoo?';

        $('a').on('click', function() { $(window).unbind("beforeunload"); });
        $('form').on('submit', function() { $(window).unbind("beforeunload"); });

        $(window).on("beforeunload", function() {
            $(window).unbind("beforeunload");
            setTimeout(function() {
                window.location = url;
            }, 0);

            return message;
        });
    });
</script>
</head>
<body>
hello world
</body>
</html>

I tested in chrome and it works as expected.

Now, I plan to use zepto.js instead of jquery.js for certain reason.

By changing

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

to

<script src="zepto.min.js"></script>

I realize the code no longer work. There is no JavaScript error. But, event function of beforeunload doesn't never triggered.

I suspect $(window).on behaves differently among jquery and zepto

May I know, how can I get $(window).on("beforeunload", function() { works for zepto?


Solution

  • I don't have the time right now to do an in deep analysis of the zepto and jquery code.

    The problem is the way zepto is handling the return values of the event callback.

    mdn: beforeunload says that it has to be used that way:

    e.returnValue = confirmationMessage;     // Gecko and Trident   
    return confirmationMessage;              // Gecko and WebKit
    

    This is done automatically by jQuery but not by Zepto.

    Setting the returnValue by hand seems to work fine in Chromium and Firefox:

    $(window).on("beforeunload", function(e) {
        e.returnValue = message;
        return message;
    });
    

    But there still might be cross-browser issues. So either you use native addEventListener instead of zepto or you need to do some cross browser testing.