angular 6中的浏览器选项卡关闭事件仅在调试模式下有效 [英] Browser tab close event in angular 6 only works in debug mode
问题描述
我正在尝试捕获我的angular 6应用程序中的浏览器事件,例如关闭选项卡和刷新.它在调试模式下可以正常工作,但是如果我关闭调试模式并运行应用程序,则无法正常工作.下面是一段代码
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
,则可以使用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屋!