Reputation: 1534
I have my site with angularjs SPA. When user clicks on refresh button or press F5/ Ctrl + F5 to I want to prevent, or abort page reloading. Unfortunately, solution with onbeforeunload
and onunload
events are not working. Actually, they are called, event.preventDefault()
line is reached, there are any messages in console, but browser continue to load page.
My current module .run()
code:
let window = angular.element($window);
window.on("beforeunload", (event) => {
event.preventDefault();
}).on("unload", (event) => {
event.preventDefault();
});
// This is just for sure that I have my handlers registered
$window.onbeforeunload = (event) => {
event.preventDefault();
}
$window.onunload = (event) => {
event.preventDefault();
}
How can I really handle this in angular?
UPDATE
I need this for reloading actual state instead of page. So when user clicks refresh I want to just reload current state with $stateProvider
and not to reload the whole page
Upvotes: 8
Views: 16165
Reputation: 3159
Check out what Mozilla has to say about unload events. It looks like it is not possible to prevent a refresh like you want to. The only think that you can do is to ask the user if he/she really wants to leave the page.
I guess you could reload the current state in the case the user answers that he/she does not want to leave the current page.
window.onbeforeunload = function(event) {
// do some stuff here, like reloading your current state
//this would work only if the user chooses not to leave the page
return 'why would you do that???';
}
I have created a fiddle for you.
Upvotes: 10