Jump to content

[SOLVED] window.onbeforeunload


onlyican

Recommended Posts

Hi

 

We were trying to work out if we can prompt the user if they want to close a page before closing. I didn;t think it was possible.

 

I can not remember what site I was on but when I clicked close, I got a prompt, Are you sure you want to leave..

 

Quick look at the code and came accross

window.onbeforeunload

 

Excellent, email that to me at work, look tomorrow.

NOw I have forogotton the website and can not get this to work

 

Within the head tag I have

 

window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}

 

But nothing happens.

 

Please help me to where I am going wrong.

Link to comment
https://forums.phpfreaks.com/topic/181843-solved-windowonbeforeunload/
Share on other sites

window.onbeforeunload = confirmExit;
function confirmExit()
{
confirm("You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?");
}

 

I have this on my site, it is inside of <body> and </body>

 

<script type="text/javascript">
				var workIsDone = false;
				window.onbeforeunload = confirmBrowseAway;
				function confirmBrowseAway() {
				  if (!workIsDone) {
				    return "CAREFUL! Discard this entry?\n" +
				    "This blog entry will not be saved.";
				  }
			}
				function save() {
				  workIsDone = true;
				}
function disableForm(theform) {
if (document.all || document.getElementById) {
	for (i = 0; i < theform.length; i++) {
		var tempobj = theform.elements[i];
		if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
			tempobj.disabled = true;
	}
	return true;
}
}


</script>

 

Then on the html form I incorperate the save() function so if they user wanted to save it it saves and then the workisdone is set to true and it allows you to save and move on.

 

<form name="form" method="POST" onSubmit="save(); return disableForm(this);" action="your action here">

 

The disable form helps prevent multiple sibmits etc, and can be omitted.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.