最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending a notification on window close - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

I 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

发布评论

评论列表(0)

  1. 暂无评论