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

2

22

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

Torrell answered 16/1, 2015 at 12:19 Comment(1)
check routechange event as single page application is for not refreshing page.Mohur
C
38

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.

Cornerwise answered 16/1, 2015 at 13:22 Comment(1)
Yes, this is a perfect hack. You can use the onbeforeunload, and handle it. BTW, I don't feel the need to inject the window dependency.Farinaceous
C
0

August 2024 Update

While I still think that @Christina's answer is the most correct one, I just wanted to note that the user experience will not be the same between reloading the page and navigating to a new route.

Now most (if not all) modern browsers no longer allow you to write a custom message when reloading the page. The browser will now show a default message before reloading the page when using preventDefault() and allow the user to suppress further dialogs when reloading.

See this article

Cochleate answered 1/8 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.