Last active
November 1, 2022 09:28
-
-
Save anghelalexandra/5517c603ab2d6ade51313537644f9a06 to your computer and use it in GitHub Desktop.
Extract device ID from Google Analytics _ga cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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