简体   繁体   中英

How do I send an AJAX request upon page unload / leaving?

window.onbeforeunload = function() {
    return $j.ajax({
        url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
    });
}

this what I have, but it returns an alert with [object Object]

how do I just execute the AJAX?

note: when I just don't return anything, the server doesn't show that it is receiving the ajax request.

You don't need to return anything, just fire the ajax call.

window.onbeforeunload = function(e) {
    e.preventDefault();
    $j.ajax({ url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + &time_on_page=" + getSeconds()
    });
}

If you are using jQuery, you can try binding to the .unload() event instead.

onbeforeunload allows you to return a string, which is shown in the 'Do you want to leave' confirmation. If you return nothing, the page is exited as normal. In your case, you return the jqXHR object that is returned by the JQuery ajax method.

You should just execute the Ajax call and return nothing.

Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page).

In the rare case when you need to send information as the user is navigating away from the page (as Aaron says, avoid this where possibl), you can do it with sendBeacon . sendBeacon lets you send data to your server without holding up the page you're doing it in:

window.addEventListener("unload", function() {
  navigator.sendBeacon("/log", yourDataHere);
});

The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).

Note that the unload event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange as well.

Why are you returning the reference of function to global pool? It should be like this:

window.onbeforeunload = function() {
 $j.ajax({
    url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
 });
}

To the best of my understanding, the onbeforeunload function will only return an alert. This was done to prevent the annoying popups of a few years back.

I was building a chat client a while back and the only way i could figure out to do something like this is to do a setInterval function that updated a timestamp, then checked for timed out users and removed them. That way users that didnt "check in" within a certain interval would be removed from the room by other users still logged in.

Not pretty, or ideal, but did the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM