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.
-
what you mean by tab? is it a component? – Anto Antony Jun 05 '18 at 10:11
-
No. tab means browser window tab. – Amith Dissanayaka Jun 05 '18 at 10:23
-
I need to call http request "https://*********.com/sessionStatus" when closing browser tab – Amith Dissanayaka Jun 05 '18 at 10:36
-
this one is similar to your question https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser/37642657 – Anto Antony Jun 05 '18 at 10:38
-
https://stackoverflow.com/questions/38999842/angular-2-execute-code-when-closing-window/39005933 – Anto Antony Jun 05 '18 at 10:40
-
same as my question. But this solution is not work for when tab closing. Can't display any alert also when tab closing. It works only when refreshing. – Amith Dissanayaka Jun 05 '18 at 15:05
-
Sorry, It was my mistake. Your answer is worked for me. Thank You. – Amith Dissanayaka Jun 05 '18 at 15:25
-
Is there any method to find $event is refresh event of tab close event – Amith Dissanayaka Jun 05 '18 at 15:43
1 Answers
'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)