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>
@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