0

I'm creating a analytics system where I need to send the page read time in seconds with a jquery ajax call on page unload. But the AJAX call is not working on page unload (it's working on load, click etc).

Browser: Chrome 104 Android

My JavaScript:

document.addEventListener('beforeunload', function() {

        $.ajax({

            type: "POST",

            url: '', /* Current Page */

            data: {

                report: 120 /* Just Example */

            },

            cache:false,

            async: false

        });

    });
  • 2
    [`async: false` has been deprecated for a long time](/q/11448011/4642212). Consider using the [Beacon API](//developer.mozilla.org/en/docs/Web/API/Beacon_API) instead. – Sebastian Simon Dec 03 '22 at 11:32
  • I found a latest blog post with `async : false`, URL https://www.webdevsplanet.com/post/building-custom-web-analytics-tool –  Dec 03 '22 at 11:34
  • Does this answer your question? [window.onbeforeunload ajax request in Chrome](https://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome) – Ken Lee Dec 03 '22 at 11:40

1 Answers1

1
$(window).on('unload', function () {
    $.ajax({
        type: "POST",
        url: '', /* Current Page */
        data: {
            report: 120 /* Just Example */
        },
        cache: false,
        async: false
    });
});
Albin C S
  • 340
  • 1
  • 5