When a user leaves one page of my website, there should be a warning message which gives the user the option to stay on the page:
“Are you sure that you want to close this page?”
It doesn’t matter if the next page is an internal or external page.
I thought this could be done with the onUnload event handler, couldn’t it?
<body onunload="confirmClose()">
The confirmClose() function must then show a message box with two buttons so that the user can choose between “Really leave” or “Stay”.
function confirmClose() {
return confirm('Really leave this page?')
}
But this function can’t stop the unload, right?
Do you have a solution for my problem? Thanks in advance!
You can add an
onbeforeunloadevent. Note that it can only return a text string to include in the dialog the browser will display when the event is called. You can’t tweak the dialog beyond that, nor can you trigger your ownconfirmas you’re trying to do.I’d note that this is very, very annoying behaviour except in a few specific situations. Unless you’re saving me from significant data loss with this, please don’t do it.