Skip to content

Instantly share code, notes, and snippets.

@philcon93
Last active November 27, 2019 05:03
Show Gist options
  • Save philcon93/90518c3b51f759dc9133b05ec26e9720 to your computer and use it in GitHub Desktop.
Save philcon93/90518c3b51f759dc9133b05ec26e9720 to your computer and use it in GitHub Desktop.
Beacon analytics
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);
};
@philcon93
Copy link
Author

philcon93 commented Nov 25, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment