Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@anghelalexandra
Last active November 1, 2022 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anghelalexandra/5517c603ab2d6ade51313537644f9a06 to your computer and use it in GitHub Desktop.
Save anghelalexandra/5517c603ab2d6ade51313537644f9a06 to your computer and use it in GitHub Desktop.
Extract device ID from Google Analytics _ga cookie
/**
* Get a browser cookie
*
* @param string cname = The cookie name
* @return string = The cookie value or an empty string ("") if the cookie doesn't exist
*/
getCookie = function(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
};
/**
* Get the device id from the Google Analytics cookie.
*/
getGoogleAnalyticsDeviceId = function() {
var gaCookie = getCookie("_ga");
if (gaCookie === "") {
return null;
}
// Parse the _ga cookie value to the right format.
var lastElements = gaCookie.split(".").slice(-2);
if (lastElements.length == 2) {
return lastElements.join(".");
}
return null;
};
var deviceId = getGoogleAnalyticsDeviceId();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment