Skip to content

Instantly share code, notes, and snippets.

@justusbluemer
Last active March 14, 2024 12:52
Show Gist options
  • Save justusbluemer/08d3b4735212d17585d1a336d65b5cc5 to your computer and use it in GitHub Desktop.
Save justusbluemer/08d3b4735212d17585d1a336d65b5cc5 to your computer and use it in GitHub Desktop.
gtagGeolocation
async function gtagGeolocation() {
try {
// Fetch the script from the specified URL
const response = await fetch('https://www.googletagmanager.com/gtag/js?id=G-CRGJ6H77X9&l=dataLayer&cx=c');
const text = await response.text();
// Use regex to extract the Base64 string
const regex = /=JSON\.parse\(zb\("(.+?)"\)\)/;
const matches = regex.exec(text);
if (matches && matches[1]) {
// Decode the Base64 string to get the geolocation data
const base64String = matches[1];
const decodedString = atob(base64String);
const geolocationData = JSON.parse(decodedString);
// Return the country and region from the geolocation data
return { country: geolocationData['0'], region: geolocationData['1'] };
} else {
console.log('Base64 string not found');
return null;
}
} catch (error) {
// Log any errors that occur during the fetch or processing
console.error('Error fetching or processing:', error);
return null;
}
}
// Geolocate!
gtagGeolocation().then(result => {
if (result) {
console.log(result);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment