English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

By using Javascript, HTML, ASP or any other browser scripting language, is it possible to alert a message or do a different task before a window closes. For example, in Yahoo! Mail Beta, if you close your window while composing, it asks you if you want to leave or not. So Can I do that?

2007-02-18 10:03:42 · 1 answers · asked by otingocniindisguise 1 in Computers & Internet Programming & Design

1 answers

You use the window.onunload event in JavaScript to fire a function when the document is being unloaded (unloaded happens when the user tries to close the window or navigate to another page). The following is very basic anonymous function:

window.onunload = function() {alert("you are now leaving");}

You can also do:

window.onunload = functionname;

function functionname()
{
//do something
}

Unloading the document can't be cancelled, but it can be overridden. If the user says "Cancel" (no), you can reload the current page - effectively keeping them where they are.

To get the Confirm dialog box, you use the confirm() function -

if(!confirm('Are you sure you want to leave?'))
{
window.location = window.location;
}

So, the whole thing together:

window.onunload = function() { if(!confirm('Are you sure you want to leave?')) {window.location = window.location;}}

Simply put this inside