(function (context, trackingId, options) { | |
const history = context.history; | |
const doc = document; | |
const nav = navigator || {}; | |
const storage = localStorage; | |
const encode = encodeURIComponent; | |
const pushState = history.pushState; | |
const typeException = 'exception'; | |
const generateId = () => Math.random().toString(36); | |
const getId = () => { | |
if (!storage.cid) { | |
storage.cid = generateId() | |
} | |
return storage.cid; | |
}; | |
const serialize = (obj) => { | |
var str = []; | |
for (var p in obj) { | |
if (obj.hasOwnProperty(p)) { | |
if(obj[p] !== undefined) { | |
str.push(encode(p) + "=" + encode(obj[p])); | |
} | |
} | |
} | |
return str.join("&"); | |
}; | |
const track = ( | |
type, | |
eventCategory, | |
eventAction, | |
eventLabel, | |
eventValue, | |
exceptionDescription, | |
exceptionFatal | |
) => { | |
const url = 'https://www.google-analytics.com/collect'; | |
const data = serialize({ | |
v: '1', | |
ds: 'web', | |
aip: options.anonymizeIp ? 1 : undefined, | |
tid: trackingId, | |
cid: getId(), | |
t: type || 'pageview', | |
sd: options.colorDepth && screen.colorDepth ? `${screen.colorDepth}-bits` : undefined, | |
dr: doc.referrer || undefined, | |
dt: doc.title, | |
dl: doc.location.origin + doc.location.pathname + doc.location.search, | |
ul: options.language ? (nav.language || "").toLowerCase() : undefined, | |
de: options.characterSet ? doc.characterSet : undefined, | |
sr: options.screenSize ? `${(context.screen || {}).width}x${(context.screen || {}).height}` : undefined, | |
vp: options.screenSize && context.visualViewport ? `${(context.visualViewport || {}).width}x${(context.visualViewport || {}).height}` : undefined, | |
ec: eventCategory || undefined, | |
ea: eventAction || undefined, | |
el: eventLabel || undefined, | |
ev: eventValue || undefined, | |
exd: exceptionDescription || undefined, | |
exf: typeof exceptionFatal !== 'undefined' && !!exceptionFatal === false ? 0 : undefined, | |
}); | |
if(nav.sendBeacon) { | |
nav.sendBeacon(url, data) | |
} else { | |
var xhr = new XMLHttpRequest(); | |
xhr.open("POST", url, true); | |
xhr.send(data); | |
} | |
}; | |
const trackEvent = (category, action, label, value) => track('event', category, action, label, value); | |
const trackException = (description, fatal) => track(typeException, null, null, null, null, description, fatal); | |
history.pushState = function (state) { | |
if (typeof history.onpushstate == "function") { | |
history.onpushstate({ state: state }); | |
} | |
setTimeout(track, options.delay || 10); | |
return pushState.apply(history, arguments); | |
} | |
track(); | |
context.ma = { | |
trackEvent, | |
trackException | |
} | |
})(window, "XX-XXXXXXXXX-X", { | |
anonymizeIp: true, | |
colorDepth: true, | |
characterSet: true, | |
screenSize: true, | |
language: true | |
}); |
This comment has been minimized.
This comment has been minimized.
@tudou-wp currently not, but I got a lot of feature requests exposing a function to add events. It shouldn't add any significant size. For all those who want to create their own version, here is the official documentation of this GA endpoint: https://developers.google.com/analytics/devguides/collection/protocol/v1/reference I'm using https://babeljs.io/en/repl to minify and convert it to a snippet. |
This comment has been minimized.
This comment has been minimized.
Any way to add the Optimize snippet to this code? |
This comment has been minimized.
This comment has been minimized.
Improvements:
|
This comment has been minimized.
This comment has been minimized.
Hi David, I find this useful. Thanks. |
This comment has been minimized.
This comment has been minimized.
Clever! Would be interested in seeing this on npm, obviously with the mga.init({...}) abstracted out. |
This comment has been minimized.
This comment has been minimized.
Great idea! Just used it to make a VuePress plugin. |
This comment has been minimized.
This comment has been minimized.
What's the |
This comment has been minimized.
This comment has been minimized.
To compliance with the GDPR and similar, we have 2 options:
This supports "anonymizeIp"... is it possible to support "allowAdFeatures"? |
This comment has been minimized.
This comment has been minimized.
FYI, I've launched a WordPress plugin based on your code... https://wordpress.org/plugins/minimal-analytics/ |
This comment has been minimized.
This comment has been minimized.
Thanks! |
This comment has been minimized.
This comment has been minimized.
Support for custom parameters, for example to implement custom dimensions, would be great. |
This comment has been minimized.
This comment has been minimized.
How to send pageview hit?
EDIT: I think only |
This comment has been minimized.
This comment has been minimized.
Will this work with the 'ga-disable-UA-XXXXXXX-X' OptOut Cookie? |
This comment has been minimized.
This comment has been minimized.
Awesome script! I am running into a similar problem than @nwellnhof, I am using it as a Nuxt plugin (similarly as https://nuxtjs.org/faq/google-analytics#how-to-use-google-analytics-), but it seems that when changing routes, no even is recorded. Typically, Nuxt tells us to add something like
Did someone verify it? |
This comment has been minimized.
This comment has been minimized.
I've created an npm packages for this, mainly for personal use: https://www.npmjs.com/package/minimal-analytics I'm also thinking about creating an even more minimal version of analytics, that does the bare minimum of tracking (i.e. only pageviews + ip) just like StatCounter in the old day. |
This comment has been minimized.
This comment has been minimized.
Any idea if this snippet functions well in an external script file? It's kind of a big block to embed on every page. edit: I've had a chance to test this. Everything seems to work just fine in a separate file. |
This comment has been minimized.
This comment has been minimized.
@martpie any luck with Nuxt.js integration? I'm in the same boat as you, just found this. |
This comment has been minimized.
This comment has been minimized.
Great script, thanks! @curtisbelt @martpie I've got it working with Nuxt.js. I've put the code in a separate js file in my static folder and included it in the head property in my nuxt.config.js file. Analytics is showing the slugs of the pages I visited. |
This comment has been minimized.
This comment has been minimized.
I'm with @waqasy: Is it possible to do something like |
This comment has been minimized.
This comment has been minimized.
Can anyone who uses this please tell me whether it only tracks pageviews or other basic stuffs like sessions and number of users? |
This comment has been minimized.
This comment has been minimized.
Hi @kaknut! Yes, pageviews are tracked correctly as well as session and number of users. Example of something that's not being tracked: RUM performance. |
This comment has been minimized.
This comment has been minimized.
Fantastic script! You can probably make it support hashed routes out of the box by adding |
This comment has been minimized.
This comment has been minimized.
any idea how to implement sampleRate in this script? |
This comment has been minimized.
This comment has been minimized.
btw, I just realized this fails in Safari incognito mode due to localStorage not available
|
This comment has been minimized.
This comment has been minimized.
I created one that's compatible with the cookie format of the Google analytics.js script. It's very minimal, just under 700 bytes when minified https://gist.github.com/janispritzkau/c9fe29242af53fd1b10a847da78b3406 |
This comment has been minimized.
This comment has been minimized.
What about using URLSearchParams instead of serialize? |
This comment has been minimized.
This comment has been minimized.
Yep. It would make sense if you're only targeting browsers that support ES6 and newer. I used it in my tiny analytics script |
This comment has been minimized.
This comment has been minimized.
How do I track event with inline js in minimal analytics? |
This comment has been minimized.
This comment has been minimized.
How do I make this script work with Turbolinks? It seems like it cannot capture pageview if I am using Turbolinks with it. |
This comment has been minimized.
This comment has been minimized.
Hello, can somebody advise:
|
This comment has been minimized.
This comment has been minimized.
@idarek, the code above is in its original form. The version on https://minimalanalytics.com/ is minified. Use the minified version in production to produce a smaller page. |
This comment has been minimized.
This comment has been minimized.
Anybody about the other part? Is it possible to add timings?
|
This comment has been minimized.
This comment has been minimized.
@idarek The snippet is very well thought but you can use it as a template to build your own and even convert it to a function and call it whenever you want, I've used this as a base for my react projects and converted it as a hook. |
This comment has been minimized.
This comment has been minimized.
Installed on my website without any modification. Firstly though that will lose insight into average session duration (i know that is not accurate but always something) but I didn't which is great. Nice improvement recorded for the website as well. Great job! |
This comment has been minimized.
This comment has been minimized.
Thanks for this great Snippet! Wondering when will GA4 be available ? |
This comment has been minimized.
This comment has been minimized.
Depends when the newer API is finalized, currently in alpha..
…On Tue, 15 Dec 2020, 15:00 huseyinkogo, ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
*Thanks for this great Snippet!*
Wondering when will GA4 be available ?
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<https://gist.github.com/443121e692175d6fc145e1efb0284ec9#gistcomment-3562190>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAAO7EW2A2DS6ORSYUFSBSLSU5MWLANCNFSM4HHJNOBQ>
.
|
This comment has been minimized.
This comment has been minimized.
Is it? https://developers.google.com/analytics/devguides/reporting/core/v4/migration#v4_1 |
This comment has been minimized.
This comment has been minimized.
I see that the last David response was 2 years ago. Is that project dead? |
This comment has been minimized.
This comment has been minimized.
Thanks for all the responses and sorry for not responding sooner. I don't have the capacity to improve this snipped further, but you can fork/use it as you like. |
This comment has been minimized.
This comment has been minimized.
Hello. Please help me. or before </script> i need to add something like this: ? |
This comment has been minimized.
This comment has been minimized.
Thanks David, ps. to people looking into v4. As I read, this is totally new Analytics and when moved into that, previous data is not transferred hence don't see the point to migrate from Universal to v4 unless you need to. For current version, I would be interested in finding some workaround for blocking /collect by various scripts and adblockers. Even Google web.dev website reporting as follow
|
This comment has been minimized.
Before I saw this, I always host ga.js locally to improve performance. I'm thinking post action to GA with nginx in the back-end.
I have the same problem like you with GTM, thank you for making this!
Could this method be used to track speed, events and goals too?