Prevent User From Closing a Window

In some situation, you might want to prevent or, at least, alert a user when he tries to close the window or browse to another URL. For example, when a user is composing a mail that is not saved yet.

if (mail.isDirty()) {
    Clients.confirmClose("Your message has not been sent.\nDiscard your message?");    
} else {
    Clients.confirmClose(null);    
}

Once the confirmClose method is called with a non-empty string, a confirmation dialog is shown up when the user tries to close the browser window, reload, or browse to another URL: