18

I would like to detect in my angular app when a user is navigating away from or reloading a page.

App (that uses some login process) should then distinguish that it was re-loaded, so user won't lose his auth data and app should be able to restore then necessary information from localStorage.

Please suggest some best techniques to "handle" browser reloading / navigation.

2 Answers 2

21

All of your javascript and in memory variables disappear on reload. In js, you know the page was reloaded when the code is running again for the first time.

To handle the reload itself (which includes hitting F5) and to take action before it reloads or even cancel, use 'beforeunload' event.

var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
    // do whatever you want in here before the page unloads.        

    // the following line of code will prevent reload or navigating away.
    event.preventDefault();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Where exactly would you put this snippet?
@Sebastialonso inside .run() function on your module. Module docs - docs.angularjs.org/api/ng/type/angular.Module
windowElement.on('beforeunload, ...) did not work for me. Did windowElement.on('onbeforeunload, ...) instead which worked as expected.
@Ben Wilde - i use your suggestions with event.preventDefault() for prevent page reloading, but also page is reloading.
3

I had the same problem, but Ben's answer didn't work for me.

This answer put me on the right track. I wanted to add a warning on some states but not all of them. Here is how I did it (probably not the cleanest way) :

window.onbeforeunload = function(event) {
   if ($state.current.controller === 'ReloadWarningController') {
      // Ask the user if he wants to reload
      return 'Are you sure you want to reload?'
   } else {
      // Allow reload without any alert
      event.preventDefault()
   }
 };

(in the ReloadWarningController definition, which had the $state injected)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.