Skip to content

Instantly share code, notes, and snippets.

@LRENZ
Created July 22, 2024 15:24
Show Gist options
  • Save LRENZ/ba10f38825fd56c15452aefb8b9a760f to your computer and use it in GitHub Desktop.
Save LRENZ/ba10f38825fd56c15452aefb8b9a760f to your computer and use it in GitHub Desktop.
GET GA4 client id
// Constant for Measurement ID without G-
const MEASUREMENT_ID = 'G-DKNEXDCMS2';
// Function to read cookies
function get_ga_clientid_from_cookies() {
var cookie = {};
document.cookie.split(';').forEach(function(el) {
var splitCookie = el.split('=');
var key = splitCookie[0].trim();
var value = splitCookie[1];
cookie[key] = value;
});
return cookie["_ga"].substring(6);
}
// Function to get GA4 client ID
function getGA4ClientID() {
// Check if gtag is defined
if (typeof gtag === 'function') {
return new Promise((resolve, reject) => {
console.log('Using gtag API to get client ID');
gtag('get', `${MEASUREMENT_ID}`, 'client_id', (clientID) => {
if (clientID) {
console.log('Client ID from gtag API:', clientID);
resolve(clientID);
} else {
console.log('Failed to get client ID from gtag API');
reject('Failed to get client ID from gtag API');
}
});
});
} else {
// Fallback to reading cookies if gtag is not defined
console.log('gtag is not defined, falling back to reading cookies');
const clientID = get_ga_clientid_from_cookies();
if (clientID) {
console.log('Client ID from cookies:', clientID);
return Promise.resolve(clientID);
} else {
console.log('Failed to extract client ID from cookies');
return Promise.reject('Failed to extract client ID from cookies');
}
}
}
// Example usage
getGA4ClientID()
.then((clientID) => {
// Do something with the client ID
console.log(clientID);
})
.catch((error) => {
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment