Created
July 11, 2017 10:42
-
-
Save panayotoff/8f5ef8d4e9912080e233f3829585c447 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
import {TRACKING_ID} from '../appConfig'; | |
import store from '../store/store'; | |
let gaAvailable = false; | |
let ga = null; | |
const loadAnalytics = () => { | |
const isPageSpeedBot = (navigator.userAgent.indexOf('Speed Insights') !== -1); | |
const blockTracking = store.getters.track.toString() === 'false'; | |
if (blockTracking || isPageSpeedBot) { | |
return false; | |
} | |
loadAnalyticsScript(); | |
}; | |
const loadAnalyticsScript = () => { | |
(function (i, s, o, g, r, a, m) { | |
i['GoogleAnalyticsObject'] = r; | |
i[r] = i[r] || function () { | |
(i[r].q = i[r].q || []).push(arguments) | |
}, i[r].l = 1 * new Date(); | |
a = s.createElement(o), | |
m = s.getElementsByTagName(o)[0]; | |
a.async = 1; | |
a.src = g; | |
m.parentNode.insertBefore(a, m) | |
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); | |
// ga('create', 'UA-90362874-1', 'auto'); | |
// ga('send', 'pageview'); | |
// ga = window.ga; | |
window.ga(onAnalyticsReady); | |
}; | |
const onAnalyticsReady = () => { | |
gaAvailable = true; | |
//-------------------------------------------------------------- | |
// | |
//-------------------------------------------------------------- | |
window.ga('create', { | |
trackingId: TRACKING_ID, | |
cookieDomain: 'auto' | |
}); | |
track({ | |
hitType: 'pageview' | |
}); | |
}; | |
const track = (data) => { | |
if (gaAvailable) { | |
const isPageView = data.hitType === 'pageview' && data.pagePath; | |
if (isPageView) { | |
window.ga('set', { | |
page: data.pagePath | |
}); | |
window.ga('send', { | |
hitType: 'pageview' | |
}); | |
} | |
else { | |
window.ga('send', data); | |
} | |
} | |
}; | |
//https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications | |
const trackPageView = (pagePath) => { | |
track({ | |
hitType: 'pageview', | |
page: pagePath | |
}); | |
}; | |
//https://developers.google.com/analytics/devguides/collection/analyticsjs/events | |
const trackEvent = (data) => { | |
track(Object.assign({hitType: 'event'}, data)); | |
}; | |
//https://developers.google.com/analytics/devguides/collection/analyticsjs/social-interactions | |
const trackSocial = (data) => { | |
track(Object.assign({hitType: 'social'}, data)); | |
}; | |
export { | |
loadAnalytics, | |
track, | |
trackPageView, | |
trackEvent, | |
trackSocial | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment