我正在研究Angle 5项目。这样我想在关闭标签页时调用API。如何使用“ beforeunload”或任何技术。
'beforeunload'将在刷新页面,关闭标签或关闭浏览器时触发。
@HostListener('window:beforeunload', ['$event'])
beforeUnload(e: Event) {
e.returnValue = false;
}
您可以设置'e.returnValue = false;'或“返回假”;以显示来自浏览器的确认对话框。但是自2016年4月以来,您无法通过返回字符串显示自定义消息。请参阅https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs
您可以在beforeunload事件中设置'navigator.sendBeacon()'以发送POST API。但是,“ navigator.sendBeacon()”只能使用POST API,并且不能设置自定义标头(如令牌)。 (请参阅Navigator.sendBeacon() to pass header information)
某些文档建议使用具有属性'keepalive'的访存:
const token = localStorage.getItem('token');
fetch(url, {
headers: {
'content-type': 'application/json',
'authorization': token
},
method: 'POST',
body: JSON.stringify(data),
credentials: 'include',
mode: 'no-cors',
keepalive: true,
})
但是在chrome M78中,keepalive现在不起作用,已报告但未修复。(请参阅https://bugs.chromium.org/p/chromium/issues/detail?id=835821)