angular 6 中的浏览器选项卡关闭事件仅适用于调试模式 [英] Browser tab close event in angular 6 only works in debug mode

查看:16
本文介绍了angular 6 中的浏览器选项卡关闭事件仅适用于调试模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 angular 6 应用程序中捕获浏览器事件,例如 tab-close 和 refresh.它在调试模式下工作正常,但如果我关闭调试模式并运行应用程序,它就无法工作.下面是一段代码

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?

推荐答案

您需要使用 beforeunload 而不是 unload.beforeunload 更可靠,并在文档及其资源即将卸载时触发,而 unload 在页面已经卸载时触发.

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.

您的 endSession() 必须是同步的,因为浏览器不会在调用任何回调时等待.据我所知,angular http 服务不提供同步 http 调用,但您可以使用 XMLHttpRequest 自行完成:

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

另请查看这篇文章.如果您的客户端浏览器支持该功能,您可能可以使用 navigator.sendBeacon.

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

这篇关于angular 6 中的浏览器选项卡关闭事件仅适用于调试模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆