我正在做angular 5项目。以便在关闭页签时调用API。如何使用"beforeunload“或任何技术来做到这一点。
发布于 2019-12-02 17:55:50
“‘beforeunload”将在刷新页面、关闭标签或关闭浏览器时触发。
@HostListener('window:beforeunload', ['$event'])
beforeUnload(e: Event) {
e.returnValue = false;
}您可以设置'e.returnValue = false;‘或'return 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接口。但是'navigator.sendBeacon()‘只能POST接口,不能设置像token这样的自定义头部。(请参阅Navigator.sendBeacon() to pass header information)
一些文档建议使用带有属性‘keepalive’的fetch:
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,
})但是keepalive现在不能在chrome M78中工作,这是报告但没有修复的。(请参考https://bugs.chromium.org/p/chromium/issues/detail?id=835821)
https://stackoverflow.com/questions/50697417
复制相似问题