Can I pop up a confirmation dialog when the user is closing the window in Safari/Chrome?

This works perfectly for me in both Chrome and Safari:

<html><body><p>Test</p>
<script>window.onbeforeunload = function() { return "Sure?"; }</script>
</body></html>

When I try to close the window, I get the prompt.


StackOverflow itself uses onbeforeunload, and it works fine for me in Safari:

function setConfirmUnload(a){window.onbeforeunload=a?function(){return a}:null}

I checked it in chrome and it seems to be working fine using this:

<body onunload="alert('x');" onbeforeunload="test1();">