Update March 2025: I have added 2 new integrations with OneTrust, one to automatically load Optimizely once consent has been given; and one that auto-reload the page upon consent. See below the details.
As concerns around privacy grows, you may have been asked to make sure that Optimizely complies with your company’s cookie policy.
While the actual policy varies, it is best practice to wait for the user’s consent before letting Optimizely store any user data.
In a nutshell, this means we’ll disable Optimizely altogether, but we will only start serving experiments and sending data back to Optimizely servers if the user has given consent.
Let’s see how.
The Approach
Here’s how this integration will work in a nutshell:
- Upon a visitor’s first visit, we will turn off Optimizely so no cookies or data is stored in the browser, nor is any experiment activated on the page
- When a visitor gives consent, we will either load Optimizely immediately or wait until the next page load, or auto-reload the page
- Upon this next page load, Optimizely will run normally and activate any eligible experiments.
I’d recommend to review your own company’s privacy policy as well as each of the countries it is operating in, to ensure that you comply with local laws.
Step-by-step process
Okay, now we know the approach we’ll take, let’s implement the integration technically.

To start, Onetrust creates a cookie called OptanonConsent which stores the current cookie policy acceptance status, as such:

This groups parameter tells us which cookie categories have been accepted or denied.
For example, C0001:1 means that cookie category 0001 has been accepted (set to 1 = true). C0002:0 means that cookie category 0002 have not yet been accepted (set to 0 = false).
In most scenarios, Optimizely will fit into cookie category 0003 (subject to your company’s cookie policy).
So on every page, Optimizely will check for the group C0003 and based on the return value we get (0 or 1), we will either disable Optimizely altogether (if we get a 0) or let Optimizely run normally (if we get a 1).
Step 1: Read the OptanonConsent cookie
To read the cookie, we’ll use a utility function called getCookie.
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
That’s it for step 1!
Step 2: Check for OptanonConsent values
Once we have the cookie value, we can go ahead and check for the cookie consent level and ensure it matches our policy.
Notice the line const allowedCookies which you’ll have to replace with your company cookie policy acceptance level. Here we are relying on cookie acceptance for cookies of category 3 to decide whether or not to run Optimizely Web:
(() => {
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(name) === 0) {
return c.substring(name.length);
}
}
return "";
}
const optanonConsent = getCookie("OptanonConsent");
if (!optanonConsent || !optanonConsent.includes("2:1")) {
window.optimizely = window.optimizely || [];
window.optimizely.push({ type: "disable" });
}
})();
If you need Optimizely to be counted as part of necessary, functional or targeting cookies, you need to update the first line replacing the value 002 with the value of your cookie category (001, or 003, or 004, or 005).
Step 2: Add above script to Project Javascript
Add this at the top of your Project Javascript and the integration implementation will be completed.
That’s it!
Update 1: Load Optimizely immediately after consent
This updated method uses OneTrust’s native OnConsentChanged event listener to automatically reload the entire page when consent status changes.
Here are the main benefits:
- Real-time response to consent changes without waiting for the next page load
- Works especially well for single-page applications (SPAs)
- Experiments get delivered right on consent
- No disruptive user experience, no page reload
This is ideal for websites that need immediate compliance with changed consent settings, particularly those with multiple third-party scripts that need to be enabled/disabled based on consent.
If a user accepts cookies, and then changes his mind, and updates his consent level, this integration will disable Optimizely. So Optimizely is constantly up to date with OneTrust’s consent levels.
On the downside, because by the time a user accepts cookie consent most of the page has already loaded, you may experience flickering.
Here’s the code to add to your Project JS, keep in mind to update the variable cookiesAllowed at the beginning of the script to reflect your cookie policy, as well as adding your projectId at the top of the file:
(() => {
// Optimizely project ID - replace with your actual project ID
const optimizelyProjectId = "YOUR_OPTIMIZELY_PROJECT_ID";
const optimizelyScriptUrl = `https://cdn.optimizely.com/js/${optimizelyProjectId}.js`;
const cookiesAllowed = "2:1";
function integrationLogger(message) {
console.log("OneTrust integration logger: " + message);
}
// Function to get cookies
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(name) === 0) {
return c.substring(name.length);
}
}
return "";
}
// Function to load Optimizely script
function loadOptimizelyScript() {
// Remove any existing Optimizely script
const existingScript = document.querySelector('script[src*="cdn.optimizely.com/js/"]');
if (existingScript) {
existingScript.remove();
}
// Load Optimizely script
const script = document.createElement('script');
script.src = optimizelyScriptUrl;
script.async = true;
document.head.appendChild(script);
integrationLogger("Optimizely script loaded");
}
// Function to handle consent changes
function handleConsentChange() {
const updatedConsent = getCookie("OptanonConsent");
const updatedConsentAllowed = updatedConsent && updatedConsent.includes(cookiesAllowed);
integrationLogger("Consent status changed:", updatedConsentAllowed ? "Allowed" : "Not allowed");
// Only reload if consent status actually changed
if (updatedConsentAllowed) {
integrationLogger("Consent status changed, allowing Optimizely to run - reloading Optimizely script...");
loadOptimizelyScript();
} else {
integrationLogger("Consent status not allowing Optimizely to run - no reload needed, disabling Optimizely just in case...");
// Ensures the optimizely object is defined globally
window['optimizely'] = window['optimizely'] || [];
// API call
window["optimizely"].push({
"type": "disable"
});
}
}
/**
* Simple function that returns a promise which resolves when OneTrust and OnConsentChanged are available
* @param {number} timeout - Maximum time to wait in milliseconds
* @returns {Promise} - Resolves when OneTrust is ready, rejects on timeout
*/
function whenOneTrustReady(timeout = 10000) {
return new Promise((resolve, reject) => {
// Check if already available
if (typeof window.OneTrust !== 'undefined' &&
typeof window.OneTrust.OnConsentChanged === 'function') {
integrationLogger("OneTrust already available");
resolve();
return;
}
// Set timeout for rejection
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
reject(new Error("Timed out waiting for OneTrust"));
}, timeout);
// Poll for OneTrust availability
const checkInterval = setInterval(() => {
if (typeof window.OneTrust !== 'undefined' &&
typeof window.OneTrust.OnConsentChanged === 'function') {
clearInterval(checkInterval);
clearTimeout(timeoutId);
integrationLogger("OneTrust now available");
resolve();
}
}, 200); // Check every 200ms
});
}
function initOneTrustIntegration() {
// Get initial consent status to compare against later
const initialConsent = getCookie("OptanonConsent");
let initialConsentAllowed = initialConsent && initialConsent.includes(cookiesAllowed);
integrationLogger("Initial consent status:", initialConsentAllowed ? "Allowed" : "Not allowed");
if (!initialConsentAllowed) {
integrationLogger("Performance cookies not allowed on initial load, disabling Optimizely and setting up OneTrust listener");
// Ensures the optimizely object is defined globally
window['optimizely'] = window['optimizely'] || [];
// API call
window["optimizely"].push({
"type": "disable"
});
} else {
integrationLogger("Performance cookies allowed, letting Optimizely run");
}
// Initialize the listener when OneTrust is ready
whenOneTrustReady()
.then(() => {
// Register the callback with OneTrust.OnConsentChanged
window.OneTrust.OnConsentChanged(handleConsentChange);
integrationLogger("Successfully registered OneTrust.OnConsentChanged listener");
})
.catch((error) => {
integrationLogger("Failed to detect OneTrust:", error);
});
}
initOneTrustIntegration();
})();
Update 2: Force page auto-reload on cookie consent
This is very similar to the previous method above, except that we auto-reload the page once we detect a consent change that matches the allowedCookies specified.
Take the code below, and add this to your Project JS:
(() => {
const cookiesAllowed = "2:1";
function integrationLogger(message) {
console.log("OneTrust integration logger: " + message);
}
// Function to get cookies
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(name) === 0) {
return c.substring(name.length);
}
}
return "";
}
// Function to handle consent changes
function handleConsentChange() {
const updatedConsent = getCookie("OptanonConsent");
const updatedConsentAllowed = updatedConsent && updatedConsent.includes(cookiesAllowed);
integrationLogger("Consent status changed:", updatedConsentAllowed ? "Allowed" : "Not allowed");
// Only reload if consent status actually changed
if (updatedConsentAllowed) {
integrationLogger("Consent status changed, allowing Optimizely to run - reloading page...");
window.location.reload();
} else {
integrationLogger("Consent status not allowing Optimizely to run - no reload needed, disabling Optimizely just in case...");
// Ensures the optimizely object is defined globally
window['optimizely'] = window['optimizely'] || [];
// API call
window["optimizely"].push({
"type": "disable"
});
}
}
/**
* Simple function that returns a promise which resolves when OneTrust and OnConsentChanged are available
* @param {number} timeout - Maximum time to wait in milliseconds
* @returns {Promise} - Resolves when OneTrust is ready, rejects on timeout
*/
function whenOneTrustReady(timeout = 10000) {
return new Promise((resolve, reject) => {
// Check if already available
if (typeof window.OneTrust !== 'undefined' &&
typeof window.OneTrust.OnConsentChanged === 'function') {
integrationLogger("OneTrust already available");
resolve();
return;
}
// Set timeout for rejection
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
reject(new Error("Timed out waiting for OneTrust"));
}, timeout);
// Poll for OneTrust availability
const checkInterval = setInterval(() => {
if (typeof window.OneTrust !== 'undefined' &&
typeof window.OneTrust.OnConsentChanged === 'function') {
clearInterval(checkInterval);
clearTimeout(timeoutId);
integrationLogger("OneTrust now available");
resolve();
}
}, 200); // Check every 200ms
});
}
function initOneTrustIntegration() {
// Get initial consent status to compare against later
const initialConsent = getCookie("OptanonConsent");
let initialConsentAllowed = initialConsent && initialConsent.includes(cookiesAllowed);
integrationLogger("Initial consent status:", initialConsentAllowed ? "Allowed" : "Not allowed");
if (!initialConsentAllowed) {
integrationLogger("Performance cookies not allowed on initial load, disabling Optimizely and setting up OneTrust listener");
// Ensures the optimizely object is defined globally
window['optimizely'] = window['optimizely'] || [];
// API call
window["optimizely"].push({
"type": "disable"
});
} else {
integrationLogger("Performance cookies allowed, letting Optimizely run");
}
// Initialize the listener when OneTrust is ready
whenOneTrustReady()
.then(() => {
// Register the callback with OneTrust.OnConsentChanged
window.OneTrust.OnConsentChanged(handleConsentChange);
integrationLogger("Successfully registered OneTrust.OnConsentChanged listener");
})
.catch((error) => {
integrationLogger("Failed to detect OneTrust:", error);
});
}
initOneTrustIntegration();
})();
Quality Assurance: How to test that it is working
You can test it by going to your website URL, in an incognito browser window and add the following query parameter to your URL:
?optimizely_log=DEBUG
This enables the Optimizely log and ensures that you can see under the hood of Optimizely.
If all is working, you will see the following messages:

Then accept cookies, reload the page and these messages will no longer show.
If you are able to see all that, congratulations, the integration is working!
Comparison and Use Case Guide
I’ve also included a comparison section that helps readers decide which integration method is best for their specific needs:
- Basic Integration – Simple and straightforward for most websites
- Optimizely auto-reload Integration – For immediate compliance with consent changes
- Page auto-reload integration