选项卡关闭角度5时的API调用

时间:2018-06-05 10:04:47

标签: angular5

我正在开展角度5项目。所以我想在关闭标签时调用API。如何使用" beforeunload"或任何技术。

1 个答案:

答案 0 :(得分:0)

刷新页面,关闭标签或关闭浏览器时会触发“ 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