I have two apps, App1 and App2.
App2 is embedded as an iframe in App1, so App1 is parent app which embeds App2.
When user closes App1 from browser, I want to trigger an api in App2.
I tried using 'unload'
event in App2, but that is not getting triggered when App2 closes (am checking by putting debugger point on event listener function, which gets called when standalone App2 gets closed).
Is there a way to accomplish this? Thanks
Asked
Active
Viewed 193 times
0

hack
- 1,403
- 2
- 14
- 20
1 Answers
0
Historically trying to make asynchronous requests in unload events has never been reliable
For that reason navigator.sendBeacon(url, data) was created.
It works in the background even after page or tab is gone and helps solve a lot of the reliability problems of using unload events.
With the sendBeacon() method, the data is transmitted asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation.
I've never used it in the disappearing iframe scenario like yours but believe it would solve your issue

charlietfl
- 170,828
- 13
- 121
- 150
-
Hi, thanks for your reply. The api I want to call on unload is protected by a gateway, so need to pass auth header as well. From what I read, we cannot send auth header in sendBeacon call. Is there any workaround that case? – hack Sep 21 '20 at 08:25
-
Only thing I can think of is use a proxy endpoint you control and can accept auth data in a post and create auth header to send to other api – charlietfl Sep 21 '20 at 08:47
-
Thanks for your suggestion. I tried with fetch with keepAlive true and it seems to be working fine – hack Sep 21 '20 at 12:07
-
Curious how you used fetch()? – charlietfl Sep 21 '20 at 14:49
-
Hello, I followed this answer to implement fetch with keepAlive true https://stackoverflow.com/a/56169544/6002185 – hack Sep 22 '20 at 00:23