1

I need to do Async Http Post to external URL when user close the browser or navigates to a different page.

So, I attached a JS handler to BeforeUnload event.

Sometimes it gets triggered and sometimes it doesn't. I'm checking on chrome. Whenever I try to debug the script via inspector, it always work fine.

I must use JavaScript only (no external library like jQuery etc.)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ankur Nigam
  • 83
  • 1
  • 8

2 Answers2

4

It is fired only if there was ANY interaction of the user with the site. Without ANY interaction event(e.g. click, not hover), onbeforeunload won't be fired.

aermin
  • 341
  • 3
  • 8
0

You can't use async operations in the beforeunload or unload events. In order for your script to work you have to make it synchronous. That would be easy by adding the async: false property to your ajax function (or similar if you are using a different approach). It might be that because you are postponing the disposal of the window when you are debugging that it works then. I've also read that in order to call a function you need to return something at the end of the event. Usually if you return a string that text will be displayed in a popup. I think you can find more useful info here: window.onbeforeunload not working

Community
  • 1
  • 1
astian
  • 684
  • 7
  • 18