This is usually done on the client side using JavaScript, because it is not possible to intercept the beforeunload event on the server side when the end user leaves the page.
Here is a specific example using the jQuery JavaScript library (otherwise you will have 10 times more code to match crossbrowser compatibility and work seamlessly with ajax re-render):
<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 into your <h:head> template or just put it in some script.js file that you will include <h:outputScript> .
Balusc
source share