Javascript "onbeforeunload": user-friendly save-pr

Started by Darren Dirt, December 02, 2005, 03:31:06 PM

Previous topic - Next topic

Darren Dirt

I thought this might be handy to any of you ever working on a web app, AJAX or whatever, that has a user editing some data on a form and you want to handle their accidental clicking-of-the-close-box or hitting a navigation button by mistake. Instead of them losing the data, you should probably prompt them to "save" first, right? And even if they save, they might want to "cancel" the closing/leaving of the window, right?



Voila.



Try this, it "feels right". It uses only "onbeforeunload", doesn't use "onunload", and it takes the guesswork out of what that event handler needs to return :)



- - -



JS onbeforeunload - A Template For USER-FRIENDLY Save-Prompting.html



[html to try for yourself and modify those 3 global strings to your heart's desire]




<html>

<title>onbeforeunload: A Template For USER-FRIENDLY Save-Prompting</title>

</head>

<body>

<h3>onbeforeunload: A Template For USER-FRIENDLY Save-Prompting</h3>

<script>



MSG_CLOSING_FIRST_PROMPTSAVE="Leaving webpage... Do you wish to save first?";



MSG_CLOSING_LAST_WITHOUTSAVING="Last chance to abort! Really leave this page without saving?";



MSG_CLOSING_LAST_FILESAVED="OK, file has been saved. Really leave this page now?";



function handleBeforeUnload()

{

var rv=MSG_CLOSING_LAST_WITHOUTSAVING;

if(confirm(MSG_CLOSING_FIRST_PROMPTSAVE))

{

/*do the save here -- AJAX, IFRAME, Image.src, whatever...*/

rv=MSG_CLOSING_LAST_FILESAVED;

};

return rv;

};



window.onbeforeunload=handleBeforeUnload;



</script>



Click me: <a href="http://google.com/">http://google.com/</a> (then hit BACK button and try clicking the other buttons)



</body>

</html>




[/html]
_____________________

Strive for progress. Not perfection.
_____________________