Add
<SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
window.onbeforeunload = unloadMess;
function unloadMess(){
mess = "Thanks for visiting.\nYou will now be returned to our regularly scheduled program."
return mess;
}
//-->
</SCRIPT>
before your html body.
But there is a issue as the the event can be invoked using the form submit method. which is
the ‘__doPostBack’ script and it contains the line
‘theform.submit()’.
And I just found a way you can detect if it is the Back button clicked by
<script>
function onBeforeUnloadAction(){
return "Think twice before you leave!";
}
window.onbeforeunload = function(){
if((window.event.clientX<0) ||
(window.event.clientY<0)){
return onBeforeUnloadAction();
}
}
</script>
The way to avoid it is that you add a client click script to set event.cancelBubble property to true. Here is some code:
Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", @"
<script>
var postback= false;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(postback == true)
event.cancelBubble = true;
else
return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";
}
</script>");
VB .NET
Page.ClientScript.RegisterStartupScript(GetType(String), "ConfirmClose", "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "<script>" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "var postback= false; window.onbeforeunload = confirmExit;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "function confirmExit()" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "{" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "if(postback == true)" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "event.cancelBubble = true;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "else" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "} " & Chr(13) & "" & Chr(10) & "" & Chr(9) & "</script>")
then my save button contains the following aspx markup:
OnClientClick="postback=true;return true;"
http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript
http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html