Is there a way to trigger a $http.get request when the page is closed? I encountered an issue where promises cannot be resolved because once the final method returns, the page is destroyed.
The challenge lies in the fact that onbeforeunload does not wait for promises to resolve. Here is an example of why it does not work:
window.onbeforeunload = function(
$http.get('http://someth.ing/update-state?page=unloaded').then(function(){
// This code will never be executed as the promise never gets resolved before the page is unloaded.
}
}
While synchronous HTTP methods can be used as a workaround, the real question is how to synchronize/wait for promises to resolve in this scenario.
One potential solution could involve implementing something like this:
window.onbeforeunload = function(){
var ready = false;
$http.get('http://someth.ing/update-state?page=unloaded').then(function(){
ready=true;
}
// The only way I see to sync a promise here is through this loop:
while(!ready) angular.noop();
// The big question: has the $http call been made to the server now? Can we safely return from this method and allow the browser to exit the page?
}
RFC