Prototype Script onbeforeunload when leaving a page

December 14, 2007

<script type="text/javascript">
  var FormWatch = Class.create();
  FormWatch.prototype = {
     initialize : function(form, options) {
        this.submitted = false;
        this.form = $(form);
        // Let's serialize this.form and store it...
        this.formcontents = $(form).serialize();
        // Observe beforeunload event...
        Event.observe(this.form, 'submit', function() {this.submitted =
  true; }.bind(this));
        Event.observe(window, 'beforeunload',
  this.confirmExit.bind(this));
     },confirmExit : function(ev) {
        this.newcontents = this.form.serialize();
        if ((this.formcontents != this.newcontents) && !
  (this.submitted)) {
           ev.returnValue = "You have unsaved information.";
           //return Event.stop(ev);
        }
     }
  }

  </script>
  <script type="text/javascript">
        new FormWatch('property_form');
   </script>

This will shout at you if you leave a form when you have edited it.