Last active
July 10, 2018 08:04
-
-
Save jpvincent/8761957d0319ce4eb0df1bf1ebb155ea to your computer and use it in GitHub Desktop.
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
// 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