8

I have a javascript object which I need global to my angularjs application. When the application is about to be unloaded (due to a page refresh or some other scenario), I would like to persist the object to browser storage. I believe adding the object to $rootScope would fulfill the first requirement of making the object global, but writing the object to storage during the onbeforeunload event, would require access to the $rootScope variable. Is it possible to detect a page unload event in angularjs?

user1491636
  • 2,355
  • 11
  • 44
  • 71
  • have you considered using something like https://github.com/grevory/angular-local-storage or https://github.com/gsklee/ngStorage – Vadim Dec 08 '14 at 22:41

1 Answers1

13

This should do it, but I also suggest avoiding $rootScope as global state is discouraged, and you might also wrap localStorage in a service so that it can be injected and mocked for testing.

.run([
  '$window',
  '$rootScope',
  function($window, $rootScope) {
    $window.addEventListener('beforeunload', function() {
      localStorage.myValue = $rootScope.myValue;
    });
  }
]);
m59
  • 43,214
  • 14
  • 119
  • 136
  • Thanks. And would the event for page completed loading be `load`? – user1491636 Dec 09 '14 at 22:19
  • @user1491636 I don't think you should be using that event. If you want something to run at the beginning of your Angular app, just put it in a `run` block as in my example here. – m59 Dec 09 '14 at 22:41
  • Your solution does not solve the problem, because even by clicking cancel it is called. – Ivan Ferrer Feb 02 '18 at 14:32
  • @IvanFerrer Clicking cancel on what? Nothing in the post or my answer involves any buttons, that I know of. – m59 Feb 02 '18 at 19:59