Can beforeunload/unload be used to send XmlHttpRequests reliably

后端 未结 3 1277
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 10:57

recently, I had the urgent requirement to give my server a notice, that a specific page of my webapp is about to get closed. \"Easy peasy\" I thought, beforeu

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 11:36

    Take a look at navigator.sendBeacon(), which allows you to reliably send data to a server even when the page is unloading. It's currently in a draft specification and supported by Firefox 31, Chrome 39 (behind a flag from 37), behind a flag in Opera 24.

    You could "sort of" polyfill it using something like the following:

    navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
        var xhr = new XMLHttpRequest();
    
        // Need to send synchronously to have the best chance of data getting
        // through to the server
        xhr.open('POST', url, false);
        xhr.send(data);
    };
    

    Further reading:

    • HTML5 Rocks article

提交回复
热议问题