7

In angularjs is possible handle the user clicking the Refresh button on the browser? There is any method that the framework expose to the developer?

Thanks

Tom
  • 4,007
  • 24
  • 69
  • 105
  • Not sure what you intend to "handle". But a quick Google search lists the following discussions: 1. Info on Angular $routeProvider: http://stackoverflow.com/questions/17324902/how-does-angular-application-handle-refresh-page-and-could-we-use-history-on-lo 2. Disabling refreshes: http://stackoverflow.com/questions/2482059/disable-f5-and-browser-refresh-using-javascript 3. Handle route events: http://stackoverflow.com/questions/16344223/angularjs-cancel-route-change-event – DavidP May 28 '14 at 13:03

2 Answers2

7

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 Something

   //After this will prevent reload or navigating away.
   event.preventDefault();
});
gtzinos
  • 1,205
  • 15
  • 27
0

You can use $routeChageStart:

 $rootScope.$on('$routeChangeStart', function () {
            alert('refresh');
        });
Yaroslav Osetrov
  • 894
  • 1
  • 10
  • 13
  • 6
    As far as I know, this is not what OP asked for. This event fires every time the view is changed, not specially on user refresh. – Sebastialonso Dec 15 '14 at 03:05
  • 1
    Though the answer is wrong, it does not deserve a negative penalty – Siva Tumma Apr 21 '17 at 11:11
  • I don't think this would work; the `beforeunload` is pretty tough on accepting changes in behaviour from javascript. e.g. with angular 7 the *somehow* equivalent approach with `canDeactivate` doesn't work. – Adrian Dec 08 '18 at 17:08