Skip to content

Instantly share code, notes, and snippets.

@mbaersch
Last active January 17, 2023 07:03
Show Gist options
  • Save mbaersch/677cfad72592631eea4d385116c91a63 to your computer and use it in GitHub Desktop.
Save mbaersch/677cfad72592631eea4d385116c91a63 to your computer and use it in GitHub Desktop.
Write Google Analytics Client ID to localStorage
<!--
Replace existing standard gtag.js tracking-code with this
snippet in order to store the Client ID in localStorage and use this ID when present
converted for direct code implementation from Simo Ahava´s solution for GTM; see
https://www.simoahava.com/analytics/use-localstorage-client-id-persistence-google-analytics/
for details
Client IDs will survive deletion of cookies by user or ITP 2.1
- replace UA-xxxxx-y with your own property id (2 instances)
- adjust special configuration like custom dimensions if present in existing code
- tracker is initialized with option 'anonymize_ip': true. Delete (2 instances) if not needed
- you do not need this comment or the other comments in the code below in a live source code - delete them after implementation!
NOTE: this solution only works for single-host domains like www.domain.com.
If you measure multiple subdomains like blog.domain.com, www.domain.com, app.domain.com
in a single property, localStorage is no solution!
-->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxx-y"></script>
<script>
var GA_TRACKING_ID = 'UA-xxxxx-y';
var localStorageCid = {
objectName: 'ga_client_id',
expires: 1000*60*60*24*365*2
};
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
if (window.localStorage) {
var lsCid;
var jsonObj = window.localStorage.getItem(localStorageCid.objectName) || '{}';
var obj = JSON.parse(jsonObj);
var now = new Date().getTime();
if (obj.clientId && obj.expires) {
if (now <= obj.expires) {
lsCid = obj.clientId;
}
}
//initialize - but do not send auto-hit
//add your own additional options here if present in existing code
gtag('config', GA_TRACKING_ID, { 'anonymize_ip': true, 'send_page_view': false, 'client_id': lsCid});
//pageview gets sent now with callback for storing the Client ID
gtag('event', 'page_view', {
'event_callback': function() {
var tracker_id = GA_TRACKING_ID.replace(/-/g, '_');
var tracker = window.ga.getByName('gtag_'+tracker_id);
var _lsc_clientId = tracker.get('clientId');
var _lsc_obj = JSON.stringify({
clientId: _lsc_clientId,
expires: new Date().getTime() + localStorageCid.expires
});
window.localStorage.setItem(localStorageCid.objectName, _lsc_obj);
}
});
}
else {
//add your own additional options here if present in existing code
gtag('config', GA_TRACKING_ID, { 'anonymize_ip': true });
}
</script>
<!--
Replace existing standard Universal Analytics tracking-code with this
snippet in order to store the Client ID in localStorage and use this ID when present
converted for direct code implementation from Simo Ahava´s solution for GTM; see
https://www.simoahava.com/analytics/use-localstorage-client-id-persistence-google-analytics/
for details
Client IDs will survive deletion of cookies by user or ITP 2.1
- replace UA-xxxxx-y with your own property id
- adjust special configuration like custom dimensions below if present in existing code
- you do not need this comment or the other comments in the code below in a live source code - delete them after implementation!
NOTE: this solution only works for single-host domains like www.domain.com.
If you measure multiple subdomains like blog.domain.com, www.domain.com, app.domain.com
in a single property, localStorage is no solution!
-->
<script>
var GA_TRACKING_ID = 'UA-xxxxx-y';
var localStorageCid = {
objectName: 'ga_client_id',
expires: 1000*60*60*24*365*2
};
(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');
if (window.localStorage) {
var lsCid;
var jsonObj = window.localStorage.getItem(localStorageCid.objectName) || '{}';
var obj = JSON.parse(jsonObj);
var now = new Date().getTime();
if (obj.clientId && obj.expires) {
if (now <= obj.expires) {
lsCid = obj.clientId;
}
}
ga('create', GA_TRACKING_ID, { 'clientId': lsCid });
ga(function(tracker) {
var _lsc_clientId = tracker.get('clientId');
var _lsc_obj = JSON.stringify({
clientId: _lsc_clientId,
expires: new Date().getTime() + localStorageCid.expires
});
window.localStorage.setItem(localStorageCid.objectName, _lsc_obj);
});
}
else {
ga('create', GA_TRACKING_ID, 'auto');
}
//Comment out if no anonymization required
ga('set', 'anonymizeIp', true);
//add additional configuration here. Example
//ga('set', 'dimension1', 'foo');
ga('send', 'pageview');
</script>
@cr-solutions
Copy link

Hallo, ich erhalte leider folgende Fehlermeldung: window.ga.getByName is not a function
Jemand eine Idee?

Danke im Voraus

@mbaersch
Copy link
Author

Hallo,

Jemand eine Idee?

es scheint so, als würde sich etwas unter der Haube von gtag.js tun; vielleicht geht es nun weg von analytics.js als Unterbau und Richtung App+Web... Jedenfalls steht der Tracker offenbar erstaunlicherweise noch nicht zur Verfügung, wenn der Callback stattfindet. Ich zitiere hier eine Mail eines anderen Users des Codes mit dem gleichen Problem mit seiner Lösung, die ich nicht getestet habe:

I solved the error implementing timeout function...
function createFunctionWithTimeout(callback, opt_timeout) {
var called = false;
function fn() {
if (!called) {
called = true;
callback();
}
}
setTimeout(fn, opt_timeout || 1000);
return fn;
}

And then in your code:
gtag('event', 'page_view', {
'event_callback': function() {
createFunctionWithTimeout(function() {
...............
code here
...............
}
}
});

I hope this can help someone else...


Es gibt sicher nun einen neuen Weg, an die Client ID zu kommen, aber mir fehlt gerade die Zeit, dies zu erproben. Wer einen Hinweis hat, darf gern aushelfen.

@elizabethjoankelly
Copy link

Does this replace cookie storage with localStorage? Or does it use localStorage as a backup if cookies were deleted?

@mbaersch
Copy link
Author

mbaersch commented Jun 9, 2021

Does this replace cookie storage with localStorage? Or does it use localStorage as a backup if cookies were deleted?

It uses localStorage instead of cookies. So with later iterations of ITP, this makes no difference any longer. For ePrivacy cookies or localStorage will not change the game either

@elizabethjoankelly
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment