我试图在我的 angular 6 应用程序中捕获浏览器事件,如 tab-close 和 refresh。它在调试模式下工作正常,但如果我关闭调试模式并运行应用程序,它就无法工作。下面是一段代码
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();
}
对于这个问题,我可能有什么问题?
您需要使用beforeunload
而不是unload
. beforeunload
更可靠并在文档及其资源即将卸载时unload
触发,而在页面已经卸载时触发。
您endSession()
必须是同步的,因为浏览器不会在调用任何回调时等待。据我所知,angular http 服务不提供同步 http 调用,但您可以通过以下方式自行完成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
如果您的客户端的浏览器支持该功能,您可能可以使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句