Javascript confirm close window

Hello forums. Why is this code always returns true? :

function closeIt(){
if(confirm(“Are you sure you want to close this window”)){
return true;
}else{
return false;
}
}

</script>

<body onunload=“closeIt()”>

I’m trying to make a routine that will confirm the user if he wants to close the pop up window.

Thanks

It’s not that it always returns true, it’s that even when it returns false, it won’t stop the window from closing.

The event that he wants to trigger on instead, is the onbeforeunload event.

Also, instead of


if(confirm("Are you sure you want to close this window")){
    return true;
}else{
    return false;
}

You can simplify that and just return the result from the confirm statement.


return confirm("Are you sure you want to close this window");

is the onbeforeunload event.

Thought that was IE only?

Nope, it’s all modern browsers too.

Sample code:


window.onbeforeunload = function () {
    return "Are you sure that you want to leave this page?";
}

Demo page:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Onbeforeunload test</title>
</head> 
<body> 
<p>This is a test of onbeforeunload. Please click this link to <a href="http://www.google.com">google.com</a></p>
<script type="text/javascript">
window.onbeforeunload = function () {
    return "Are you sure that you want to leave this page?";
}
</script>
</body> 
</html> 

Unfortunately - since its main use is to shove more spam in your face when you are trying to leave a spammy web page.

It depends on how it’s approached.

Google’s Gmail for example uses it very wisely. When you are writing an email it says that your message has not been sent if you try to close the window part-way through.

I agree that there are a few sites where it is useful but its misuse is so widespread that either disabling it completely or automatically confirming without bothering to read it are probably very common and so it doesn’t necessarily serve its intended purpose even when used appropriately.