Skip to content

Instantly share code, notes, and snippets.

@robisatthefunction
Last active July 14, 2023 19:25
Show Gist options
  • Save robisatthefunction/98afff1cffd067dde17b5b9e62fc9625 to your computer and use it in GitHub Desktop.
Save robisatthefunction/98afff1cffd067dde17b5b9e62fc9625 to your computer and use it in GitHub Desktop.
// This code would go in a script above the Optimizely snippet! You will need to replace the cookie names with the names of your compliance cookies, they are just placeholders for the general logic that can be used.
// https://support.optimizely.com/hc/en-us/articles/4410284332685-Project-Settings-jQuery-and-Project-JavaScript-settings-in-Optimizely
// Declare function necessary to get cookies by name
function getCookie(cookieName) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [key,value] = el.split('=');
cookie[key.trim()] = value;
});
return cookie[cookieName];
}
var setCookie = function(c_name,value,exdays,c_domain) {
c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/";
};
// Disable Optimizely completely if visitor has opted out of functional cookies
// [MUST CHANGE] Domain parameter of setCookie() function
// https://docs.developers.optimizely.com/web/docs/opt-out
if(getCookie('acceptFunctional') == 'doesNotAcceptFunctionalCookies'){
// This sets the optimizelyOptOut cookie which will disable Optimizely from running
window.optimizely = window.optimizely || [];
window["optimizely"].push({
"type": "optOut",
"isOptOut": true
});
} else if (getCookie('acceptFunctional') == 'acceptsFunctionalCookies' && getCookie('optimizelyOptOut') == 'true'){
// This deletes the optimizelyOptOutCookie once the user has opted in to functional cookies which allows Optimizely to execute again
setCookie('optimizelyOptOut',1,-1,'.domain.com');
}
// Stop Optimizely tracking events from sending if the visitor has opted out of analytics tracking, and send them if they have opted in
// https://docs.developers.optimizely.com/web/docs/hold-events
// https://docs.developers.optimizely.com/web/docs/send-events
if(getCookie('acceptTracking') == "doesNotAcceptTracking"){
window.optimizely = window.optimizely || [];
window.optimizely.push({type: "holdEvents"});
} else {
window.optimizely = window.optimizely || [];
window.optimizely.push({type: "sendEvents"});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment