Skip to content

Instantly share code, notes, and snippets.

@utilmind
Created January 9, 2021 07:21
Show Gist options
  • Save utilmind/f5d2147f3491238df2464c3fae060553 to your computer and use it in GitHub Desktop.
Save utilmind/f5d2147f3491238df2464c3fae060553 to your computer and use it in GitHub Desktop.
Google Analytics without cookies
// https://medium.com/swlh/how-to-use-google-tag-manager-and-google-analytics-without-cookies-7d041c73cc76
// https://developers.google.com/tag-manager/devguide
(function() {
window.dataLayer = window.dataLayer || [];
var GA_MEASUREMENT_ID = "UA-XXXXXXXXX-X",
GA_LOCAL_STORAGE_KEY = "ga:clientId",
clientId = localStorage.getItem(GA_LOCAL_STORAGE_KEY),
gtag = function() {
dataLayer.push(arguments);
};
gtag("js", new Date());
// checks if user was already connected and loads client_id from localstorage
if (!clientId) {
// creates client_id and saves it in localStorage -> currently random number better would be a uuid
localStorage.setItem(GA_LOCAL_STORAGE_KEY, clientId = Date.now() + "-" + Math.random());
}
// creates new tracker with same client_id as the last time the user visited
gtag("config", GA_MEASUREMENT_ID, {
// send_page_view: true, // it's true by default
client_storage: "none", // don't use cookies
client_id: clientId,
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment