When I close the browser, I have to perform some server side functions.
If any exception occurs while performing the server side functions, I have to show an alert message "Operation Unsuccessful" and in that case the browser should not close.
When I close the browser, I have to perform some server side functions.
If any exception occurs while performing the server side functions, I have to show an alert message "Operation Unsuccessful" and in that case the browser should not close.
Actually, you can NOT prevent the user from closing the window.
you can however alert him/her with your message, asking the user to stay or leave the page,
this done by binding to onbeforeunload
event.
var showAlert = false;
window.onbeforeunload = function(){
$.ajax({
url: "serversideprcess.aspx",
async : false
}).done(function ( data ) {
if(data !="success")
showAlert = true;
}).fail(function(){
showAlert = true;
});
if(showAlert){
return "Operation unsuccessful";
}
}
the ajax request must be synchronous: async : false
You can't.
You cannot prevent a browser window from closing at all. Ever. Neither can you perform any work that takes time (like an HTTP request) within an onbeforeunload
handler -- all you're really allowed to do is display a confirmation dialog.
Perhaps you can use this code
<html>
<head>
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save your stuff?"
}
}
function unhook() {
hook=false;
}
</script>
</head>
<body>
<a href="http://google.com">external link</a>
</body>
</html>
window.onbeforeunload = WindowCloseHanlder;
function WindowCloseHanlder() {
//Call ajax server code CallIntiateAjaxCalling();
if (conditionfails) {
alert("condition fails")
return false;
}
}