From f7f9d77df6c3ba64c6d880b7cfb9dd55d59a7bb3 Mon Sep 17 00:00:00 2001 From: Schuyler Duveen Date: Wed, 6 Jun 2018 11:21:28 -0400 Subject: [PATCH] use sendBeacon when available so that we can also send events reliably during beforeunload --- lib/index.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/index.js b/lib/index.js index 8728d3c..c08ecac 100644 --- a/lib/index.js +++ b/lib/index.js @@ -58,6 +58,17 @@ exports.type = cors ? 'xhr' : 'jsonp'; */ function json(url, obj, headers, timeout, fn) { + headers = headers || {}; + if (navigator.sendBeacon + && Object.keys + && Object.keys(headers).length <= 1 + && (!headers['Content-Type'] || headers['Content-Type'].indexOf('text/plain') > -1)) { + var res = navigator.sendBeacon(url, JSON.stringify(obj)); + if (fn) { + fn(res ? null : { error: 'Failed to send' }, null); + } + return; + } var req = new XMLHttpRequest; req.onerror = fn; req.onreadystatechange = done;