Is it possible for onbeforeunload()
function to wait for ajax result and move to a jsp based on the resultvalue or atleast show a message before unloading?
Use a synchronous XmlHttpRequest call ("AJAX" is a mis-nomer).
It is not good Idea to display alert box for waiting response from ajax. Generally you can use alert box for message for confirmation of Leaving page after ajax response.
For avoiding use of alert you can call Ajax synchronously for example
if(window.XMLHttpRequest) xmlHttpObj=new XMLHttpRequest();
else xmlHttpObj=new ActiveXObject("Microsoft.XMLHTTP");
if(xmlHttpObj){
xmlHttpObj.onreadystatechange=function(){
if(xmlHttpObj.readyState==4 && xmlHttpObj.status == 200){
// your logic required
}
}
xmlHttpObj.open("GET", "your request url", false); // used false for synchronous call
xmlHttpObj.send(null);
}
else{
alert("AJAX not support");
}
This is my strategy and works for me:
_number_of_active_ajax ++;
$.ajax({
url: REQUEST_URL,
timeout: 3000
})
.always(function() {
_number_of_active_ajax --;
});
window.onbeforeunload = function() {
if(_number_of_active_debounce > 0 || _number_of_active_ajax > 0)
return "Your question";
}
}
It will show a message to use if the page has an active request.
AFAIK, it is not possible. onbeforeunload
has very limited functionality, otherwise malicious sites could stop you from leaving their site.
Addendum: It is possible to show a message like 'You are leaving this page'. In that case, the beforeunload()
function must return a string.
Example
window.onbeforeunload = function() {
return 'Are you sure about that?';
}