If a variable is set to 0 and they try to exit the webpage I want it to let them leave unimpeded but if the variable is set to 1 I want a function to confirm that they want to leave and if they click OK they go on their way, but if they click Cancel they stay on the page.
This is the simple function that I expected would work:
window.onload = function() {
if(!confirm("Cancel the file transfer in progress?")) {return false}
}
But it lets them leave either way. I looked toward gMail's code for a guidance or a clue but found nothing that made sense to me.
A solution would have to avoid leaving the page even for a moment or file transfers will be interrupted.
People succeed in answering ParagramStudios's questions 26% of the time (9 successes in 34 attempts).
Answers by: Dave
I think you perhaps meant "window.onunload", but that won't fix your problem because by the time the unload event occurs, it cannot be stopped. Most modern browsers handle this problem with "onBeforeUnload". The browser will provide a default "are you sure?" box, but you can add a customized string by setting event.returnValue
window.onbeforeunload = function (evt) {
var message = 'Leaving this page will cancel the file transfer in progress';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
To include the boolean switch, just put the code in an if statement, as shown below:
window.onbeforeunload = function (evt) {
if (testvalue == 1) {
var message = 'Leaving this page will cancel the file transfer in progress';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
}
Yes I did me onunload, just mistyped it on guruza.
Thanks! Perfect answer, I had read about onbeforeunload but thought it was some IE bullsh*t. But this works in IE6,FF, and Safari.