Can beforeunload/unload be used to send XmlHttpRequests reliably

后端 未结 3 1266
爱一瞬间的悲伤
爱一瞬间的悲伤 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:25

    The thing to keep in mind is that beforeunload started as an extension by Internet Explorer. Automatically, that makes it a second-class citizen on the web. There is no specification, and browser implementation varies. For example, Firefox only partially implements it by not displaying the string, only a generic message.

    Additionally, even when fully implemented, it does not protect against all possible unload scenarios, eg, the user has terminated the processor, the browser has crashed, or the computer has been turned off. Even ignoring these extreme scenarios, I suspect that it might be possible to configure your browser to ignore such requests.

    My feeling is that you shouldn't rely on this message to save you. If this web app is internal, I would suggest training them to use the Save or Close or whatever buttons instead of just closing the tab. If it's external, maybe look into automatic saving as the user does their thing?

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-08 11:38

    Sync XHR is a top-source of browser hangs, accounting for nearly 10% of hangs: http://blogs.msdn.com/b/ieinternals/archive/2011/08/03/do-not-use-xmlhttprequest-in-synchronous-mode-unless-you-like-to-hang.aspx

    In IE, even sync XHR can be "interrupted" if the request requires Windows authentication roundtrips, or if there's a POST body to be sent. You may find that only the headers of the first unauthenticated request are sent.

    0 讨论(0)
提交回复
热议问题