I have a web application where I'm trying to send a notification to a server when the window gets closed. So far the best way I've found has been to use synchronous xhr in the onunload (as async is unreliable). Here's the code at the moment:
window.onunload = function() {
var req = new XMLHttpRequest();
req.open('GET', '/api/v1/' + id + '/close?resource=' + JSON.stringify(resource), false);
req.setRequestHeader('Authorization', localStorage.token);
req.send();
}
The only problem is when they reload the page, the page freezes for a bit (which I think is due to the xhr). Is there a better way to send notifications to the server when a window is closed?
I have a web application where I'm trying to send a notification to a server when the window gets closed. So far the best way I've found has been to use synchronous xhr in the onunload (as async is unreliable). Here's the code at the moment:
window.onunload = function() {
var req = new XMLHttpRequest();
req.open('GET', '/api/v1/' + id + '/close?resource=' + JSON.stringify(resource), false);
req.setRequestHeader('Authorization', localStorage.token);
req.send();
}
The only problem is when they reload the page, the page freezes for a bit (which I think is due to the xhr). Is there a better way to send notifications to the server when a window is closed?
Share Improve this question asked May 29, 2015 at 20:31 ZavecZavec 2153 silver badges11 bronze badges2 Answers
Reset to default 7I think better solution is use Navigator.sendBeacon
for new browsers - Chrome, Opera and Firefox - because is asynchronous and browser give you promise that will send the request.
This method addresses the needs of analytics and diagnostics code that typically attempt to send data to a web server prior to the unloading of the document.
More you can find here: https://developer.mozilla/en-US/docs/Web/API/Navigator/sendBeacon
Polyfill: https://github./miguelmota/Navigator.sendBeacon
You're looking for the beforeunload
event. The unload
event actually happens when the user es back to the page (since the event can't fire when the webpage is closed, nor before they close the tab since the document hasn't unloaded yet).
Also an additional useful tip is to encode your JSON in URL patible format: encodeURIComponent(JSON.stringify(resource))
.
See here: https://developer.mozilla/en-US/docs/Web/Events/beforeunload