2

I need to make an Ajax call when a user leaves my page.
I don't need to wait for the end of the call, I just need to notify my server with a kindly "hey, user XXX is leaving the page", without notifying the client.

Here is what I've done so far :

window.onbeforeunload = function () {
    $.ajax({
        type: "POST",
        url: myURL,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ xxx: xxx, yyy: yyy })
    });
}

This perfectly works with Chrome and Edge, but this event is not raised on Firefox.

What I've done so far :

  • I tried this SO answer, as the author claims it works and has a good score, but once again, my ajax call is not fired.
  • Add async: false without any success
  • Also tried to use beforeunload instead of onbeforeunload

Can anyone explain me how to fire my Ajax call when an user leaves a page, no matter he uses Chrome, Edge or Firefox ? Thanks in advance ?

AlexB
  • 7,302
  • 12
  • 56
  • 74
  • 1
    There is no way to guarantee the call will make it. – epascarello Nov 19 '20 at 17:25
  • The page unload process will abort the request, if it isn't responsed within a couple of nanoseconds. You can't do anything asynchronous reliably in (before)unload listeners. Use `navigator.beacon` or a synchronous call in older browsers. – Teemu Nov 19 '20 at 17:33

0 Answers0