The standard JSF implementation doesn't provide facilities for this out the box. Besides, this is more a client side issue than a server side issue, so you'll really need to grab a client side language for this such as JavaScript. Since writing crossbrowser compatible JavaScript code for this particular functional requirement isn't exactly trivial, you'd like to use a JavaScript library for this which takes this into account, like jQuery.
Here's a complete kickoff example of how you could achieve this with help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
// Set the unload message whenever any input element get changed.
$(':input').change(function() {
setConfirmUnload(true);
});
// Turn off the unload message whenever a form get submitted properly.
$('form').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 <head>
template (and preferably also refactor that raw <script>
code into its own .js
file as well which you include by src
attribute) and it'll work regardless of the page you have.