1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| export class GA { constructor(ua, cid, debug = false) { this.ua = ua; this.cid = cid; // client id this.gaApi = debug ? 'https://www.google-analytics.com/debug/collect' : 'https://www.google-analytics.com/collect'; this.version = '1'; } ga(t, ...items) { let payload = `v=${this.version}&tid=${this.ua}&cid=${this.cid}`; let params = []; switch (t) { case 'pageview': // Pageview hit type // dh -- Document hostname // dp -- Page // dt -- Title params = ['dh', 'dp', 'dt']; break; case 'event': // ec -- Event Category. Required // ea -- Event Action. Required // el -- Event label. // ev -- Event value. params = ['ec', 'ea', 'el', 'ev']; } if (params === []) return; payload = `${payload}&t=${t}`; items.forEach((v, i) => { payload = `${payload}&${params[i]}=${encodeURIComponent(v)}`; }); const request = new XMLHttpRequest(); request.open('POST', this.gaApi, true); request.send(payload); } }
const uid = 'xxxx-xxxx-xxx-xxx'; const debug = false; const gaID = 'UA-xxxxxx-x'; const gaObj = new GA(gaID, uid, debug); function sendEvent(eventCategory, eventAction, eventLabel = '', eventValue = 1) { if (store.getters.config.ga === false) return; gaObj.ga('event', eventCategory, eventAction, eventLabel, eventValue); } // dh -- Document hostname, dp -- Page, dt -- Title function sendPageview(dp, dh = '', dt = '') { if (store.getters.config.ga === false) return; gaObj.ga('pageview', dh, dp, dt); }
|