Identifying Between Refresh And Close Browser Actions

前端 未结 13 1211
孤街浪徒
孤街浪徒 2020-11-22 15:29

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now

相关标签:
13条回答
  • 2020-11-22 16:09

    Its a working solution

    export class BootstrapComponent implements OnInit {
    
      validNavigation = 0;
    
      constructor(
        private auth: AuthenticationService
      ) { }
    
      ngOnInit() {
        const self = this;
        self.registerDOMEvents();
      }
    
      registerDOMEvents() {
        const self = this;
        window.addEventListener('unload', () => {
          if (self.validNavigation === 0) {
            self.endSession();
          }
        });
        document.addEventListener('keydown', (e) => {
          const key = e.which || e.keyCode;
          if (key === 116) {
            self.validNavigation = 1;
          }
        });
      }
    
      endSession() {
        const self = this;
        self.auth.clearStorage();
      }
    }
    
    0 讨论(0)
提交回复
热议问题