I want to send a $http.get if the page gets closed. Then I stumbold upon a problem where
promises can't get resolved because if this one last method returns, the page gets destroyed.
The following does not work because onbeforeunload can't resolve promises / does not wait for them:
window.onbeforeunload = function(
$http.get('http://someth.ing/update-state?page=unloaded').then(function(){
// never called... never sent...
}
}
I know, you can use default sync HTTP Methods but the question is generally how could we sync/wait for promises to resolve here.
My idea would be something like this:
window.onbeforeunload = function(){
var ready = false;
$http.get('http://someth.ing/update-state?page=unloaded').then(function(){
ready=true;
}
// I don't see any other opportunity to sync a promise here than this:
while(!ready) angular.noop();
// big question: did $http call the server now? Can we finally return in this method to let the browser 'exit' the page?
}
RFC
onbeforeunload
, there are simply no guarantees and no supported ways to do that. Though it has its own issues, it is possible to send synchronous Ajax (at a risk of sacrificing the user experience). Usually, the better solution is to solve whatever problem you're trying to solve a different way. Some people use the close of a webSocket connection as seen on the server as a notification of when the page has been closed. – Bolyard