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

前端 未结 9 886
梦毁少年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.

    0 讨论(0)
  • 2020-11-22 05:40

    The selected answer is correct that you can't guarantee that the browser sends the xhr request, but depending on the browser, you can reliably send a request on tab or window close.

    Normally, the browser closes before xhr.send() actually executes. Chrome and edge look like they wait for the javascript event loop to empty before closing the window. They also fire the xhr request in a different thread than the javascript event loop. This means that if you can keep the event loop full for long enough, the xhr will successfully fire. For example, I tested sending an xhr request, then counting to 100,000,000. This worked very consistently in both chrome and edge for me. If you're using angularjs, wrapping your call to $http in $apply accomplishes the same thing.

    IE seems to be a little different. I don't think IE waits for the event loop to empty, or even for the current stack frame to empty. While it will occasionally correctly send a request, what seems to happen far more often (80%-90% of the time) is that IE will close the window or tab before the xhr request has completely executed, which result in only a partial message being sent. Basically the server receives a post request, but there's no body.

    For posterity, here's the code I used attached as the window.onbeforeunload listener function:

      var xhr = new XMLHttpRequest();
      xhr.open("POST", <your url here>);
      xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      var payload = {id: "123456789"};
      xhr.send(JSON.stringify(payload));
    
      for(var i = 0; i < 100000000; i++) {}
    

    I tested in:

    Chrome 61.0.3163.100

    IE 11.608.15063.0CO

    Edge 40.15063.0.0

    0 讨论(0)
  • 2020-11-22 05:44

    Try this one. I solved this problem in javascript, sending ajax call to server on browse or tab closing. I had a problem with refreshing page because on onbeforeunload function including refreshing of the page. performance.navigation.type == 1 should isolate refresh from closing (on mozzila browser).

    $(window).bind('mouseover', (function () { // detecting DOM elements
        window.onbeforeunload = null;
    }));
    
    $(window).bind('mouseout', (function () { //Detecting event out of DOM
          window.onbeforeunload = ConfirmLeave;
    }));
    
    function ConfirmLeave() {
       if (performance.navigation.type == 1) { //detecting refresh page(doesnt work on every browser)
       }
       else {
           logOutUser();
       }
    }
    
    $(document).bind('keydown', function (e) { //detecting alt+F4 closing
        if (e.altKey && e.keyCode == 115) {
            logOutUser();
        }    
    });
    function logOutUser() {
       $.ajax({
         type: "POST",
         url: GWA("LogIn/ForcedClosing"), //example controller/method
         async: false
       });
    }
    
    0 讨论(0)
提交回复
热议问题