Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ansarizafar/b8ce2b85f3cfded566b6a93a702e9850 to your computer and use it in GitHub Desktop.
Save ansarizafar/b8ce2b85f3cfded566b6a93a702e9850 to your computer and use it in GitHub Desktop.
Minimal Analytics Snippet
(function (history, trackingId, options) {
const generateId = () => {
return '_' + Math.random().toString(36).substr(2, 9);
};
const getId = () => {
if (!localStorage.cid) {
localStorage.cid = generateId()
}
return localStorage.cid;
};
const serialize = (obj) => {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
if(obj[p] !== undefined) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
}
return str.join("&");
};
const pageView = () => {
setTimeout(() => {
const data = {
v: '1',
aip: options.anonymizeIp ? 1 : undefined,
tid: trackingId,
cid: getId(),
t: 'pageview',
sd: options.colorDepth && screen.colorDepth ? `${screen.colorDepth}-bits` : undefined,
dr: document.referrer || undefined,
dt: document.title,
dl: document.location.origin + document.location.pathname + document.location.search,
ul: options.language ? (navigator.language || "").toLowerCase() : undefined,
de: options.characterSet ? document.characterSet : undefined,
sr: options.screenSize ? `${(window.screen || {}).width}x${(window.screen || {}).height}` : undefined,
vp: options.screenSize && window.visualViewport ? `${(window.visualViewport || {}).width}x${(window.visualViewport || {}).height}` : undefined
};
var xhr = new XMLHttpRequest();
xhr.open("GET", `https://www.google-analytics.com/collect?${serialize(data)}&z=${Math.random()}`, true);
xhr.send(null);
}, 10);
};
const pushState = history.pushState;
history.pushState = function (state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({ state: state });
}
pageView()
return pushState.apply(history, arguments);
}
pageView();
})(window.history, "XX-XXXXXXXXX-X", {
anonymizeIp: true,
colorDepth: true,
characterSet: true,
screenSize: true,
language: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment