Confirm exit of page

We have an application that our clients use, that is built in flash (don’t ask, i don’t know why). One of the main problems we’re having at the moment is that clients keep clicking on the back button, from force of habit, which means they leave the app and have to start again.

Is there a way with javascript that i can show a confirm box when a user clicks back (or just leaves the page), so the user can choose if they actually want to leave the page or not?

nt. This has to work on all modern browsers (well IE, mozilla and opera)

Edit: Current Code

// Add Event function
  function addEvent(elm, evType, fn, useCapture)
  {
  	// cross browser event handling for IE 5+, NS6+ and Gecko
  	if (elm.addEventListener)
  	{
  		elm.addEventListener(evType, fn, useCapture);
  		return true;
  	}
  	else if (elm.attachEvent)
  	{
  		var r = elm.attachEvent('on' + evType, fn);
  		return r;
  	}
  	else
  	{
  		elm['on' + evType] = fn;
  	}
  }
  
  // Add Listeners
  function addListeners(e)
  {
  	// window unload listener
  	addEvent(window, 'unload', exitAlert, false);
  }
  
  // Confirm exit needed
  function exitAlert()
  {
  	return confirm('Are you sure you want to leave the current page?');
  }
  
  // Init
  addEvent(window, 'load', addListeners, false);

That code works as I want except it still loads the page if you click cancel.

So it doesnt work.

haha.

That’s confusing, just use
<script>
window.onunload=function() {
return confirm(‘Are you sure you want to leave the current page?’);
}
</script>
Try that.

Two problems.

A) You can’t stop a window/tab from closing with onunload. You need to use onbeforeunload, which only seems to be supported by IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, and Firefox.

B) You can’t just use a return value when you are using DOM2 and/or IE DOM events.

  function exitAlert()
  {
    if(confirm('Are you sure you want to leave the current page?')) {
      return true;
    } else {
      if(window.event) {
        window.event.returnValue = false;
      } else {
        e.preventDefault();
      }
      return false;
    }
  }

Yeah I managed to figure out the problem with onUnload() so I’ve changed that too onBeforeUnload(), which is good enough as it only needs to work in modern browsers.

I tried to change the exitAlert() that I had to the one that you posted. It works in IE but I have to go through 2 prompts to do it, and it just loads the page in firefox, even if you click cancel.

Any other help would be great :wink:

Just for a chuckle, try this in Firefox:


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 </head>
 <body onunload="history.go(0);">
 <div style="font:bold 2em Verdana,sans-serif;">Whoaa!!</div>
 </body>
 </html>
 

Anyone?

// Cross browser event handling for IE 5+, NS6+ and Gecko
 function addEvent(elm, evType, fn, useCapture)
 {
 	if (elm.addEventListener)
 	{
 		// Gecko
 		elm.addEventListener(evType, fn, useCapture);
 		return true;
 	}
 	else if (elm.attachEvent)
 	{
 		// Internet Explorer
 		var r = elm.attachEvent('on' + evType, fn);
 		return r;
 	}
 	else
 	{
 		// nutscrape?
 		elm['on' + evType] = fn;
 	}
 }
 
 // Add Listeners
 function addListeners(e)
 {
 	// Before unload listener
 	  addEvent(window, 'beforeunload', exitAlert, false);
 }
 
 // Exit Alert
 function exitAlert(e)
 {
 	// default warning message
 	var msg = "You will lose information if it has not already been saved.";
 
 	// set event
 	if (!e) { e = window.event; }
 	if (e) { e.returnValue = msg; }
 
 	// return warning message
 	return msg;
 }
 
 // Initialise
 addEvent(window, 'load', addListeners, false);

Works in IE so far, but doesnt even bring up the confirm box in firefox

Hmm, if I remember correctly, there is a bug involving addEventListener and the beforeunload event for Firefox. It’s fixed in the latest alpha of Firefox 1.1, but for now, you may have to use:

window.onbeforeunload = exitAlert;

Go back and read my last reply again.

You failed to add “e.preventDefault();”.

Maian, could you please find where that bug is documented?

I just copied and pasted the exact code you posted and thats what happened.

I’ve sorted it now anyway, thanks guys.

You’re welcome. :slight_smile:

Could you please post the working code in case someone else asks this in the future?

Also even if it would work, you’d have to use set event.returnValue instead of returning the string when using addEventListener/attachEvent. Blame its weirdness on Microsoft.

HI can any of you guys post the right code for this I do need the code to able to do some if conditions and after the user clicks not to get out i have to be able to run some codes too. Thanks

Here what i do and what i get (by th way this happens in a iframe and i call a need to call a function in the parent window)

onBeforeunload=“if (selectedobj == null && document.getElementById(‘Adding’).value != ‘true’){ return ‘A violation is required for this citation to process correctly.’; parent.highlight(16); }”

after i get the confermation that they are not changing the screen i need to tell run parent.highlight(16); this part of the code. Any ideas, Now im getting is this error saying

An Error has occured in this dialog error 84 unspecified error.
Please help

Call parent.highlight(16) before returning. If the user chooses to go to the next page, parent.highlight(16) will end up doing nothing. If the user chooses to stay on the same page, it should take effect.

This seems to be a stale thread, but, maybe I can revive it. This code is perfect for what I am looking to do, however, is there any way to display the confirmation message if the submit button has been pressed?

Thanks in advance!

<script language=“JavaScript” type=“text/javascript”>
// Cross browser event handling for IE 5+, NS6+ and Gecko
function addEvent(elm, evType, fn, useCapture)
{
if (elm.addEventListener)
{
// Gecko
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent)
{
// Internet Explorer
var r = elm.attachEvent(‘on’ + evType, fn);
return r;
}
else
{
// nutscrape?
elm[‘on’ + evType] = fn;
}
}

// Add Listeners
function addListeners(e)
{
// Before unload listener
addEvent(window, ‘beforeunload’, exitAlert, false);
}

// Exit Alert
function exitAlert(e)
{
// default warning message
var msg = “You will lose information if it has not already been saved.”;

// set event
if (!e) { e = window.event; }
if (e) { e.returnValue = msg; }

// return warning message
return msg;

}

// Initialise
addEvent(window, ‘load’, addListeners, false);
</script>

is there any way to display the confirmation message if the submit button has been pressed?

function addEvent(getElementbyId('submit'), 'onclick', exitAlert, false)

I’ve also created a removeEvent() function, cos i don’t want the message to pop-up if i click the save or submit button:

// Cross browser event removal
            function removeEvent(elm, evType, fn, useCapture){
                if (elm.removeEventListener) {
                    // Gecko
                    elm.removeEventListener(evType, fn, useCapture);
                    return true;
                }
                else
                    if (elm.attachEvent) {
                        // Internet Explorer
                        var r = elm.detachEvent('on' + evType, fn);
                        return r;
                    }
                    else {
                        // FF, NS etc..
                        elm['on' + evType] = '';
                    }
            }

With the upper code in the head, you just have to add an onclick event to the submit or save button:

<input type="button" class="button" value="Save" onclick="removeEvent(window, 'beforeunload', exitAlert, false); location.href='../list/overview.asp'" />

Hey all,

Im new to javascript but i need to use it in my asp.net. How can I trigger a button(onclick) when the user exit the page? Can advise me on what shd i add? thks alot!!

I used some of the examples from above and created a working change listener that will alert the user before they leave the page if any changes have occurred.


<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.0 Strict//EN">
<html>
<head>
<title>Change Listener</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<script type="text/javascript">
var listenerIds = new Array("TextBox1", "Radio_0", "Radio_1", "Radio_2", "Select1", "Select2", "Checkbox_0", "Checkbox_1", "Checkbox_2", "Checkbox_3", "TextArea1");
var listenerString = "";
var needToConfirm = true;
function getListenerString ()
{
var stringValue = "";

for (var i = 0; i < listenerIds.length; i++)
{
if (document.getElementById(listenerIds[i]))
{
var elem = document.getElementById(listenerIds[i]);

if (elem.type == "text" || elem.type == "textarea")
{
stringValue += elem.value;
}
else if (elem.type == "radio" || elem.type == "checkbox")
{
if (elem.checked)
{
stringValue += elem.value;
}
}
else if (elem.type == "select-one")
{
stringValue += elem.options[elem.selectedIndex].value;
}
else if (elem.type == "select-multiple")
{
for (var j = 0; j < elem.options.length; j++)
{
if (elem.options[j].selected)
{
stringValue += elem.options[j].value;
}
}
}
}
}

return stringValue;
}
function init ()
{
listenerString = getListenerString();
}
function addEvent (elem, eventType, fn, useCapture)
{
if (elem.attachEvent)
{
// Internet Explorer
var r = elem.attachEvent('on' + eventType, fn);
return r;
}
else if (elem.addEventListener)
{
// Gecko
elem.addEventListener(eventType, fn, useCapture);
return true;
}
else
{
// Netscape
elem['on' + eventType] = fn;
}
}
function confirmExit(e)
{
if (needToConfirm && listenerString != getListenerString())
{
var msg = "You will lose any unsaved changes.";

if (!e) { e = window.event; }
if (e) { e.returnValue = msg; }

return msg;
}
}
function setConfirmException()
{
needToConfirm = false;
}
addEvent(window, 'load', init, false);
addEvent(window, 'beforeunload', confirmExit, false);
</script>
<body>
<form>
<input type="text" id="TextBox1" value="test" />
<br />
<input type="radio" name="RadioGroup" id="Radio_0" value="one" checked="checked" /> 1
<input type="radio" name="RadioGroup" id="Radio_1" value="two" /> 2
<input type="radio" name="RadioGroup" id="Radio_2" value="three" /> 3
<br />
<select id="Select1">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="mouse">Mouse</option>
</select>
<br />
<select id="Select2" multiple="multiple">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="mouse">Mouse</option>
<option value="lion" selected="selected">Lion</option>
<option value="leopard" selected="selected">Leopard</option>
</select>
<br />
<input type="checkbox" id="Checkbox_0" value="one" /> 1
<input type="checkbox" id="Checkbox_1" value="two" checked="checked" /> 2
<input type="checkbox" id="Checkbox_2" value="three" /> 3
<input type="checkbox" id="Checkbox_3" value="four" checked="checked" /> 4
<br />
<textarea id="TextArea1"></textarea>
<br />
<input type="submit" value="Submit" onclick="setConfirmException();" />
</form>
</body>
</html>