Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not prevent browser page refresh/reload in angular application

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

like image 625
Andrew Avatar asked Dec 22 '15 11:12

Andrew


1 Answers

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.

like image 82
Bruno Krebs Avatar answered Oct 24 '22 08:10

Bruno Krebs