Created
March 11, 2018 09:49
-
-
Save subversivo58/10021bb6e5a31a8683063f00cc9c28db to your computer and use it in GitHub Desktop.
navigator.sendBeacon aproach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* SendBeacon - beaultifull unopinated aproach | |
* @param {String} uri - target URL (absolute or relative) | |
* @param {Object} data - JavaScript {Object} to serialize with `JSON.stringify()` | |
* @param {String} auth - optional server authentication key/nonce to request (merge to data) | |
*/ | |
function Beacon(uri, data, auth = false) { | |
// is Chrome? | |
let isChrome = !!window.chrome && !window.opera || !navigator.userAgent.indexOf(' OPR/') >= 0 | |
try { | |
if ( auth ) { | |
data.auth = auth | |
} | |
let serializedData = JSON.stringify(data), | |
rawData = false | |
/** | |
* Chrome bug not support Blob.type === 'application/json' | |
* @see https://bugs.chromium.org/p/chromium/issues/detail?id=490015 | |
*/ | |
if ( isChrome ) { | |
rawData = new Blob([serializedData], { | |
type: 'application/x-www-form-urlencoded' | |
}) | |
} else { | |
rawData = new Blob([serializedData], { | |
type: 'application/json' | |
}) | |
} | |
// send | |
if ( rawData ) { | |
navigator.sendBeacon(uri, rawData) | |
} | |
} catch(ex) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment