creamy-sugar-16875
09/15/2023, 8:18 PMprehistoric-beard-84272
09/16/2023, 6:40 AM<script>
const COOKIE_NAME = "gbuuid";
const COOKIE_DAYS = 400; // 400 days is the max cookie duration for chrome
const getUUID = () => {
// use the browsers crypto.randomUUID if set
const genUUID = () => {
if(window?.crypto?.randomUUID) return window.crypto.randomUUID();
let randUUID = ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
return randUUID;
}
const getCookie = (name) => {
let value = `; ${document.cookie}`;
let parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
// get the existing UUID from cookie if set, otherwise create one and store it in the cookie
return getCookie(COOKIE_NAME) || genUUID();
}
// GrowthBook usage with GA4:
function setupGrowthBook(){
if (typeof window.growthbook !== "undefined" && window.growthbook.GrowthBook !== "undefined" ) {
let gbuuid = getUUID();
storeUUID(gbuuid);
startGrowthbook(gbuuid);
} else {
setTimeout(() => {
setupGrowthBook();
}, 100); // waits for 100ms before checking again
}
}
function startGrowthbook(gbuuid) {
if (!window.growthbook) return;
const { GrowthBook } = window.growthbook;
window.gb = new GrowthBook({
apiHost: "<https://cdn.growthbook.io>",
clientKey: "sdk-XXXX",
enableDevMode: true,
attributes: {
deviceId: gbuuid
},
trackingCallback: (experiment, result) => {
// TODO: Use your real analytics tracking system
console.log("Viewed Experiment", {
experimentId: experiment.key,
variationId: result.key
});
}
});
// TODO: Instrument DOM with AB test logic
gb.loadFeatures().then(function() {
// if you want to do anything after GB loads
});
}
function storeUUID(uuid) {
const setCookie = (value) => {
var d = new Date();
d.setTime(d.getTime() + 24*60*60*1000*COOKIE_DAYS);
document.cookie = COOKIE_NAME + "=" + value + ";path=/;expires=" + d.toGMTString();
}
setCookie(uuid);
}
</script>
<!-- Load GB library and then fire initialization when available -->
<script src="<https://cdn.jsdelivr.net/npm/@growthbook/growthbook/dist/bundles/index.js>" onload="setupGrowthBook()"></script>
Hope this helps!