Javascript: Confirm a page exit

krahny

New Member
Messages
25
Reaction score
0
Points
0
I want to make a page that, when the user presses the exit button, a confirmation box appears that says "Are you sure you want to exit?". If you click OK, then it closes, and if you click Cancel it dosen't. Heres the code that I have:
HTML:
<body onunload="confirm('Are you sure you want to exit?')">
When I exit with this code, though, it exits and then displays the confirmation box, witch is useless since the page has already closed.

Could someone please help me figure out a way to stop the exit, and then exits if the user presses the OK button.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
To cancel an event from an inline event handler, you need to return "false". Using DOM event registration, you'd call the event object's preventDefault method.
 

krahny

New Member
Messages
25
Reaction score
0
Points
0
To cancel an event from an inline event handler, you need to return "false". Using DOM event registration, you'd call the event object's preventDefault method.

Could you please explain to me how to do this? Perhaps some code or something.
 

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
The browser will not allow you to control whether the page closes for security reasons. Therefore, there is a built in behavior within the unonload event.
Code:
function confirm() {
  //Code to execute before page close
  return '[close message]';
}
window.onunload=confirm;
This displays a confirm box, sent by the browser, with the power to halt the page closing. Using DOM event registration leaves you to struggle between browser specific methods. This bit of code will work everywhere.
 
Last edited:

krahny

New Member
Messages
25
Reaction score
0
Points
0
The browser will not allow you to control whether the page closes for security reasons. Therefore, there is a built in behavior within the unonload event.
Code:
function confirm() {
  //Code to execute before page close
  return '[close message]';
}
window.onunload=confirm;
This displays a confirm box, sent by the browser, with the power to halt the page closing. Using DOM event registration leaves you to struggle between browser specific methods. This bit of code will work everywhere.
I tried this code, but it didn't work either.

Thanks anyway.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
It turns out you need to use the beforeunload event, which works differently than other events. The event handler returns the string to display in the confirmation dialog. Basically, do what Twinkie shows, but assign confirm to window.onbeforeunload. Note that this event isn't a standard event, but it's supported by the current versions of most of the major browsers (Opera not included).
 
Last edited:
Top