Search code examples
javascriptangularjs

How can I detect a page refresh in an angularjs single page application without configuring routes?


I need to detect a page refresh event in my single page application.


Solution

  • You can't for sure, because a browser page refresh is equivalent to exiting the app then opening it again.

    What you can do is detect the page exit event and the app open event.

    In the app.run() block inject 'window' dependency and add:

    window.onbeforeunload = function () {
       // handle the exit event
    };
    

    and on $routeChangeStart event

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      if (!current) {
        // handle session start event
      }
    });
    

    And if definitely you need to link these two events it has to be on the backend/server side ....

    I hope this helps.