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

前端 未结 9 901
梦毁少年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:31

    Basing this on other answer and this blog post.

    To make things clear, in 2018 (still today 2020), Beacon API is the solution to this issue (on almost every browser)

    Beacon Requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request.

    You can use it inside onunload event, and be confident it will be sent.

    $(window).on('unload', function() {
        
        var URL = "https://example.com/foo";
        var data = "bar";
    
        navigator.sendBeacon(URL, data);
    
    });
    

提交回复
热议问题