JavaScript, browsers, window close - send an AJAX request or run a script on window closing

前端 未结 9 898
梦毁少年i
梦毁少年i 2020-11-22 04:40

I\'m trying to find out when a user left a specified page. There is no problem finding out when he used a link inside the page to navigate away but I kind of need to mark up

9条回答
  •  死守一世寂寞
    2020-11-22 05:37

    1) If you're looking for a way to work in all browsers, then the safest way is to send a synchronous AJAX to the server. It is is not a good method, but at least make sure that you are not sending too much of data to the server, and the server is fast.

    2) You can also use an asynchronous AJAX request, and use ignore_user_abort function on the server (if you're using PHP). However ignore_user_abort depends a lot on server configuration. Make sure you test it well.

    3) For modern browsers you should not send an AJAX request. You should use the new navigator.sendBeacon method to send data to the server asynchronously, and without blocking the loading of the next page. Since you're wanting to send data to server before user moves out of the page, you can use this method in a unload event handler.

    $(window).on('unload', function() {
        var fd = new FormData();
        fd.append('ajax_data', 22);
        navigator.sendBeacon('ajax.php', fd);
    });
    

    There also seems to be a polyfill for sendBeacon. It resorts to sending a synchronous AJAX if method is not natively available.

    IMPORTANT FOR MOBILE DEVICES : Please note that unload event handler is not guaranteed to be fired for mobiles. But the visibilitychange event is guaranteed to be fired. So for mobile devices, your data collection code may need a bit of tweaking.

    You may refer to my blog article for the code implementation of all the 3 ways.

提交回复
热议问题