Link to home
Start Free TrialLog in
Avatar of calypsoworld
calypsoworldFlag for Portugal

asked on

Confirmation on window close

Hi!

I have to show a confirmation dialog to user when he tries to close the window.
The user could navigate to others pages, the message should appears only in closing windows (or tab).

I tried this but it's alerts in navigation too:

<script language="javascript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
	return " Are you sure you want to exit this page?";
}
</script>

Open in new window


How can I alert the user only when he tries to close the window (or tab)?

Thanks in advance!
Avatar of grantunwin
grantunwin


function showUnloading(evt){
evt.returnValue = "You are leaving.";
if (!confirm('Are you sure?'))
{
evt.preventDefault;
evt.stopPropagation; // this makes sure it does not bubble up
}

}
</script>

<body onbeforeunload="showUnloading(event); >
</body>

Open in new window

Hi,

I don't think you can stop the browser closing through JavaScript. Because of its different scenarios e.g. will it confirm from me when i end task the browser instance from task manager?

onBeforeunload event is called even on page refresh or the postback completes.

But you can show the dialog to user about browser is closing or perform some function calls at the time of browser is closing.
About the best one could hope for is to rely upon a global var - call it OK - and set it's initial value to TRUE.

In your navigation functions, set OK to FALSE. Then in your "onbeforeunload" function, test OK. If it is false, then you are in charge of navigation, so do not display the alert. If it is TRUE, then the user is in charge, and the alert should be shown.
<script type="text/javascript">

var OK = true;

function showUnloading(e){
    if (OK) {
        e.returnValue = "You are leaving.";
        
        if (!confirm('Are you sure?')) {
            e.preventDefault;
            e.stopPropagation; // this makes sure it does not bubble up
        }
    }
}

window.onbeforeload = showUnloading;
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Badotz
Badotz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of calypsoworld

ASKER

Thank you very much!
No worries - glad to help.