Skip to content

Instantly share code, notes, and snippets.

@subversivo58
Created March 11, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subversivo58/10021bb6e5a31a8683063f00cc9c28db to your computer and use it in GitHub Desktop.
Save subversivo58/10021bb6e5a31a8683063f00cc9c28db to your computer and use it in GitHub Desktop.
navigator.sendBeacon aproach
/**
* 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