-
-
Save philcon93/90518c3b51f759dc9133b05ec26e9720 to your computer and use it in GitHub Desktop.
Beacon analytics
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
const sendData = function(endpoint = '/endpoint', type = true) { | |
const formData = JSON.stringify({ | |
siteId: 'NETO.systemConfigs.siteId', | |
url: { | |
hostname: window.location.hostname, | |
pathname: window.location.pathname, | |
search: window.location.search | |
}, | |
entries: performance.getEntries('navigation')[0], | |
resources: performance.getEntriesByType('resource').length | |
}); | |
// Check for sendBeacon support | |
if ("sendBeacon" in navigator && type) { | |
// Beacon the requested | |
if (navigator.sendBeacon(endpoint, formData)) { | |
// sendBeacon worked! | |
} else { | |
// sendBeacon failed, use XHR instead | |
logData(endpoint, formData); | |
} | |
} else { | |
// sendBeacon not available, use XHR instead | |
logData(endpoint, formData); | |
} | |
}; | |
const logData = function(endpoint, data) { | |
const client = new XMLHttpRequest(); | |
client.open('POST', endpoint, false); // third parameter indicates sync xhr | |
client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); | |
client.send(data); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reading
What to send