Prototype Script onbeforeunload when leaving a page
December 14th, 2007 by pyrat
<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.
January 8th, 2008 at 4:53 pm
Very good tip. I like this solution—it’s quick and easy.
This works well for me on IE7 and FF2, but it doesn’t seem to work on Safari 2.0.4. (Haven’t installed beta 3 yet). I get no nag message box when refreshing/exiting the page, as Safari seems to skip the beforeunload event. I’m still investigating the problem…
Thanks
January 8th, 2008 at 4:58 pm
Yes this is right. It doesnt work on safari. If you can find a modification of this solution that works on safari I would be very grateful!
Cheers,
Alastair
January 10th, 2008 at 3:47 pm
Well, I have figured something out. I can make it work on Safari, but I’m not using Prototype’s Event observe method. Here’s three different tries:
this.currentFormState = $(’myform’).serialize(false);
// .. do stuff
// This Works on IE and FF, but not Safari
Event.observe(window, ‘beforeunload’, function (e) {
var warning = ‘The form has changed. Your changes will ‘
+ ‘be lost if you press OK.’;
var newContents = $(’myform’).serialize(false);
if ( newContents != this.currentFormState ) {
e.returnValue = warning;
Event.stop(e);
}
}.bindAsEventListener(this)
);
// This doesn’t work at all
Event.observe(window, ‘beforeunload’, function () {
var warning = ‘The form has changed. Your changes will ‘
+ ‘be lost if you press OK.’;
var newContents = $(’myform’).serialize(false);
if ( newContents != this.currentFormState ) {
return warning;
}
}.bind(this)
);
// This works on IE, FF, and Safari, but it doesn’t use
// Prototype’s Event observe method
window.onbeforeunload = function () {
var warning = ‘The form has changed. Your changes will ‘
+ ‘be lost if you press OK.’;
var newContents = $(’myform’).serialize(false);
if ( newContents != this.currentFormState ) {
return warning;
}
}.bind(this);
January 23rd, 2008 at 12:32 pm
Alistair, thanks for posting your solution – I’ve been struggling getting it to work!
February 5th, 2008 at 11:43 am
Nice peace of code, really usefull and easy to integrate!
March 14th, 2008 at 3:52 am
Thanks! The event observer was the answer I was searching for.