This ended up working just fine. Here's the code in case anyone else needs something similar.
The only other tricky part was working out how to conditionally trigger a confirm dialog onbeforeunload-- any return statement triggers the dialog, so you must only return something if you want it. So return nothing if you don't want the alert-- as shown below.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Page</title>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"></script>
</head>
<body>
<form action="" method="POST" onsubmit="formmodified=0">
<p>Test: <input type="text" name="test"></p>
<p><input type="submit" value="Submit"></p>
</form>
<script type="text/Javascript">
formmodified=0;
$('form *').change(function(){
formmodified=1;
});
window.onbeforeunload = confirmExit;
function confirmExit() {
if (formmodified==1) {
return "New information not saved. Do you wish to leave the page?";
}
}
</script>
</body>
</html>
The only limitation appears to be the restriction to only the default error message in Firefox, but that is a known bug/feature and in this case it's the right information. (But not, for example, if you were using this to inform someone that an Ajax request hadn't finished, or that a music player would stop playing, or that an upload would stop uploading...)
Bookmarks