jQuery ajax call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?

前端 未结 4 705
轮回少年
轮回少年 2021-01-20 02:37

I have a situation where on page unload I am firing a request to delete the draft of a user\'s work. This works fine until a user chooses to refresh the page, whereupon ins

4条回答
  •  我在风中等你
    2021-01-20 03:22

    Making the XHR request synchronous should delay the loading of the new page until after the request is complete. I don't know how jQuery runs its synchronous XHR requests under the hood, but here's how you can do it using plain JavaScript:

    var request = new XMLHttpRequest();
    // or new ActiveXObject("Microsoft.XMLHTTP") for some versions of IE
    request.open("GET", "/some/url", false);
    request.send(null);
    
    var result = request.responseText;
    alert(result);

    Putting that in your unload handler should make the browser wait until "/some/url" is loaded before it moves on to the next page.

提交回复
热议问题