How to detect unsaved data in form when user leaves the page?

This is normally implemented in the client side with help of JavaScript, because it’s not nicely possible to intercept on beforeunload event from the server side on when the enduser leaves the page.

Here’s a concrete example with help of the JavaScript library jQuery (otherwise you would end up with 10 times as much code to make it properly crossbrowser compatible and work seamlessly together with ajax re-renders):

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(function() {
        // Set the unload message whenever any input element get changed.
        $(':input').on('change', function() {
            setConfirmUnload(true);
        });

        // Turn off the unload message whenever a form get submitted properly.
        $('form').on('submit', function() {
            setConfirmUnload(false);
        });
    });

    function setConfirmUnload(on) {
        var message = "You have unsaved data. Are you sure to leave the page?";
        window.onbeforeunload = (on) ? function() { return message; } : null;
    }
</script>

Just paste this in your <h:head> template or just put it in some script.js file which you include by <h:outputScript>.

Leave a Comment