0

I'm working on angular 5 project. So that I want to call API when closing tab. How can use "beforeunload" or any Technic to this.

Amith Dissanayaka
  • 939
  • 3
  • 12
  • 23

1 Answers1

0

'beforeunload' would be trigger when refreshing pages, closing tab, or closing the browser.

  @HostListener('window:beforeunload', ['$event'])
  beforeUnload(e: Event) {
      e.returnValue = false;
  }

You can set 'e.returnValue = false;' or 'return false;' to show a confirm dialogue from browser. But You can not show the customized message by return string since April 2016. refer to https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs

You can set 'navigator.sendBeacon()' in beforeunload event to send a POST API. However 'navigator.sendBeacon()' can only POST API, and it can't set customized header like token. (refer to Navigator.sendBeacon() to pass header information)

Some document recommend using fetch with attribute '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,
      })

But keepalive is not working now in chrome M78, which is reported but not fixed.(refer to https://bugs.chromium.org/p/chromium/issues/detail?id=835821)