insomnia/app/analytics/google.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

import * as constants from '../common/constants';
2016-10-27 03:41:30 +00:00
let _sessionId = null;
2016-11-11 23:06:24 +00:00
export function init (userId = null) {
2016-11-10 02:40:53 +00:00
if (constants.isDevelopment()) {
2016-11-16 18:16:55 +00:00
console.log(`[ga] Not initializing for dev`);
2016-10-27 03:41:30 +00:00
return;
}
if (!_sessionId) {
2016-10-28 17:51:08 +00:00
_injectGoogleAnalyticsScript();
2016-10-27 03:41:30 +00:00
}
2016-11-10 19:08:45 +00:00
if (!window.localStorage['gaClientId']) {
window.localStorage['gaClientId'] = require('node-uuid').v4();
2016-10-27 03:41:30 +00:00
}
const _sessionId = window.localStorage['gaClientId'];
window.ga('create', constants.GA_ID, {
'storage': 'none',
'clientId': _sessionId
});
2016-10-27 03:41:30 +00:00
// Disable URL protocol check
2016-10-28 17:51:08 +00:00
window.ga('set', 'checkProtocolTask', () => null);
2016-10-27 03:41:30 +00:00
// Set a fake location
2016-10-28 17:51:08 +00:00
window.ga('set', 'location', `https://${constants.GA_HOST}/`);
2016-10-27 03:41:30 +00:00
// Track the initial page view
2016-10-28 17:51:08 +00:00
window.ga('send', 'pageview');
2016-10-27 03:41:30 +00:00
2016-11-11 23:06:24 +00:00
if (userId) {
setUserId(userId);
}
2016-11-16 18:16:55 +00:00
console.log(`[ga] Initialized for ${_sessionId}`);
2016-10-27 03:41:30 +00:00
}
2016-11-16 18:16:55 +00:00
export function setUserId (userId) {
window.ga && window.ga('set', 'userId', userId);
console.log(`[ga] Set userId ${userId}`);
}
2016-11-11 23:06:24 +00:00
export function sendEvent (...googleAnalyticsArgs) {
2016-11-10 19:08:45 +00:00
window.ga && window.ga('send', 'event', ...googleAnalyticsArgs);
2016-11-16 18:16:55 +00:00
console.log(`[ga] Send event [${googleAnalyticsArgs.join(', ')}]`);
2016-10-27 03:41:30 +00:00
}
2016-10-28 17:51:08 +00:00
function _injectGoogleAnalyticsScript () {
2016-11-10 19:08:45 +00:00
try {
(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);
2016-10-27 03:41:30 +00:00
m = s.getElementsByTagName(o)[0];
2016-11-10 19:08:45 +00:00
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
2016-11-16 18:16:55 +00:00
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
2016-11-10 19:08:45 +00:00
} catch (e) {
2016-11-16 18:16:55 +00:00
console.warn('[ga] Failed to inject Google Analytics')
2016-11-10 19:08:45 +00:00
}
2016-10-27 03:41:30 +00:00
}