Skip to content

Instantly share code, notes, and snippets.

@jpvincent
Last active July 10, 2018 08:04
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 jpvincent/8761957d0319ce4eb0df1bf1ebb155ea to your computer and use it in GitHub Desktop.
Save jpvincent/8761957d0319ce4eb0df1bf1ebb155ea to your computer and use it in GitHub Desktop.
// idée originale : https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#load_abandonment
window.__trackAbandons = () => {
// Remove the listener so it only runs once.
document.removeEventListener('visibilitychange', window.__trackAbandons);
const ANALYTICS_URL = 'https://www.google-analytics.com/collect';
const GA_COOKIE = document.cookie.replace(
/(?:(?:^|.*;)\s*_ga\s*\=\s*(?:\w+\.\d\.)([^;]*).*$)|^.*$/, '$1');
const TRACKING_ID = 'UA-XXXXX-Y';
const CLIENT_ID = GA_COOKIE || (Math.random() * Math.pow(2, 52));
// Send the data to Google Analytics via the Measurement Protocol.
navigator.sendBeacon && navigator.sendBeacon(ANALYTICS_URL, [
'v=1', 't=event', 'ec=Load', 'ea=abandon', 'ni=1',
'dl=' + encodeURIComponent(location.href),
'dt=' + encodeURIComponent(document.title),
'tid=' + TRACKING_ID,
'cid=' + CLIENT_ID,
'ev=' + Math.round(performance.now()),
].join('&'));
document.removeEventListener('visibilitychange', window.__trackAbandons);
};
document.addEventListener('visibilitychange', window.__trackAbandons);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment