Don't have time to send get request on window unload

僤鯓⒐⒋嵵緔 提交于 2019-12-08 03:49:07

问题


I want to notify the server on user closes browser window.

I tried all of the

$(window).bind("beforeunload", function() {
    $.get("${contextPath}/notify?direction=logout");
});

and

$(window).unload( function() {
    $.get("${contextPath}/notify?direction=logout");
});

and

$(window).unload(function() {
    $.ajax({
      url: "${contextPath}/notify?direction=logout"
    });
});

but neither work well, despite the fact, that it is said in manual that it probably should.

In Firefox I have no notifications only on window close, but have ones on page refresh. In Chrome I have neither.

I tried to trace this script in Firebug or Chrome Developer Tools and found, that it is starting to work if traced! So I think it does not work normally because it has no time to send request before window closed or navigated.

Is this true? How to accomplish my task?

SOLUTION

This worked:

$(window).bind("beforeunload",
    function() {
        $.ajax({
            async: false,
            url: 'notify'
        });
    }
);

回答1:


It is very tricky because the browser will not wait untill the response comes so the ajax request might get aborted.

You can try something like this in beforeunload event.

$(window).bind("beforeunload", function() {
    $.ajax({
        async: false,//This will make sure the browser waits until request completes
        url: "${contextPath}/notify?direction=logout"
    });
});



回答2:


The other answers are out of date, and cause other issues, such as unreliable signalling or delaying the load of the next page.

The best solution is to use navigator.sendBeacon: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

window.addEventListener("unload", logData, false);

function logData() {
  navigator.sendBeacon("/log", analyticsData);
}

This method addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server prior to the unloading of the document. Sending the data any sooner may result in a missed opportunity to gather data. However, ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers, because user agents typically ignore asynchronous XMLHttpRequests made in an unload handler.

To solve this problem, analytics and diagnostics code have historically made a synchronous XMLHttpRequest call in an unload or beforeunload event handler to submit the data. The synchronous XMLHttpRequest blocks the process of unloading the document, which in turn causes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance, and the result is that the user perceives that the new web page is slow to load, even though the true issue is with the previous page.




回答3:


Even if this were possible, I still wouldn't recommend it. In the event you manage to get this working it wont work in all browsers and I'd still advise against it entirely.

If you're that desperate to know when a user leaves your domain, use polling or websockets with a fallback.

You could also give cookies a short timeout and use intervals to update them periodically while on the site, tricks like that would even work.

Also, it "starts" working while traced, because the event is fired before the next page even begins loading. It's been a while, but last time I played with these events, but some browsers may execute code for a period of time while the next page loads.




回答4:


You're out of luck, it would be impossible for a user to quit a page if the JavaScript executed on page unload were blocking.

Imagine all the spam.

On some browsers, the unload event will fire, but a race condition will occur between your script and cleanup of the page.

Thanks




回答5:


I don't want to say this as a comment because , I was working on this scenario long time back. I would save all information to the server when an end-user accidentally or intentionally closes the browser. I would tell you.. It was working great.,

I said working great right ? Well it was only with Firefox and IE. It failed in many other browsers (like Opera, Safari).

So my kind advice is not to depend on these functions , as they are only browser-specific.



来源:https://stackoverflow.com/questions/9235583/dont-have-time-to-send-get-request-on-window-unload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!