Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.