How to handle / prevent browser navigation or reload in angularjs?

后端 未结 2 1108
囚心锁ツ
囚心锁ツ 2020-12-15 19:22

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

2条回答
  •  不知归路
    2020-12-15 20:10

    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();
    });
    

提交回复
热议问题