Reputation: 5679
I am trying to call this confirmation function on onbeforeunload
event but its not getting called. What am I missing here?
I am calling this inside the body tag:
<body onbeforeunload="confirmation();">
I also tried:
<body onbeforeunload="return confirmation();">
Code:
function confirmation(){
var answer = confirm('You have unsaved changes!!');
if(answer == true)
{
alert('Bye Bye!!!');
}
else{
alert('You are staying');
return false;
}
}
Upvotes: 1
Views: 11391
Reputation: 4919
Soooo.. You're trying to ask the user for confirmation when he made changes on your page that will not be saved if he leaves the page. Is that correct?
If so, then that seems to be possible. Try the following on SO. Start to write an answer on this question and then try to close the browser window.
I tested in Chrome 12, FF 4.0.1 and IE 9.
All 3 browsers show a popup window. It seems they all contain a custom text. Chrome shows the cleanest message, meaning a popup with only the custom message and 2 buttons.
In all 3 browsers trying to close the browser in any normal way triggers a popup that allows the user to choose if he maybe doesn't rather stay on the page and finish what he started. If he does want to leave, he can. (killing the browser process or a computer shutdown might not do what you would like thoug :) ).
Internet Explorer:
Firefox:
Chrome:
I would try the suggestion of hooking up a function that returns a string to the window.onbeforeunload event. Try this:
<script>
window.onbeforeunload = function (evt) {
var message = 'You have started writing or editing a post.';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
Upvotes: 3
Reputation: 360046
That's not remotely how onbeforeunload
works, and the code contains syntax errors.
window.onbeforeunload = function (e)
{
var e = e || window.event,
message = 'You have unsaved changes!!';
// For IE and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
return message;
}
Upvotes: 5