Browser tab close event in angular 6 only works in debug mode

两盒软妹~` 提交于 2019-12-10 19:30:19

问题


I am trying to capture browser events like tab-close and refresh in my angular 6 Application. It's working fine in debug mode but its not working if I close debug mode and run the application. below is the piece of code

registerDOMEvents() {
  window.addEventListener('unload', () => {
    if (this.validNavigation === 0) {
      this.endSession();
    }
  });
  document.addEventListener('keydown', (e) => {
    const key = e.which || e.keyCode;
    if (key === 116) {
      this.validNavigation = 1;
    }
  });
}
endSession() {
  this.logout();
  localStorage.clear();
}
ngOnInit() {
  this.registerDOMEvents();
}

What might me the problem for this issue?


回答1:


You need to use beforeunload instead of unload. beforeunload is more reliable and triggers when the document and its resources are about to be unloaded whereas unload fires when page is already unloading.

Your endSession() must be synchronous, since browser will not wait when any callbacks will be called. As I know angular http service doesn't provide synchronous http calls, but you can do it by yourself with XMLHttpRequest:

window.addEventListener("beforeunload", function (event) {
  var client = new XMLHttpRequest();
  client.open("POST", "http://url/to/endsession", false); // third parameter indicates sync xhr
  client.setRequestHeader("Content-Type", "application/json");
  client.send('{userId: "42"}');
  console.log('done!!!'); // outputs when a response is received 
});

Also take a look this article. Probably you can use navigator.sendBeacon if a browser of your clients supports that feature.



来源:https://stackoverflow.com/questions/54919064/browser-tab-close-event-in-angular-6-only-works-in-debug-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!