OneTrust Custom Implementation
Table of Contents
- Overview
- OneTrust JavaScript API
- Custom Banner Implementation
- Custom Preference Center
- Advanced Script Management
- Privacy Signal Integration
- Performance Optimization
- Testing and Validation
- Best Practices
- Related Documentation
Overview
This guide covers advanced customization options and API usage for OneTrust, allowing you to create tailored consent management experiences that integrate seamlessly with your website's design and functionality.
OneTrust JavaScript API
Core API Functions
OneTrust provides a comprehensive JavaScript API for custom implementations:
// Check if OneTrust is loaded
if (typeof OneTrust !== 'undefined') {
// OneTrust is available
console.log('OneTrust loaded successfully');
}
Consent Status Functions
// Check if consent banner is closed
const isBannerClosed = OneTrust.IsAlertBoxClosed();
// Check if consent is valid
const isConsentValid = OneTrust.IsAlertBoxClosedAndValid();
// Get consent status for specific category
const analyticsConsent = OneTrust.IsAlertBoxClosedAndValid('analytics');
const marketingConsent = OneTrust.IsAlertBoxClosedAndValid('marketing');
Event Handling
// Listen for consent changes
OneTrust.OnConsentChanged(function() {
console.log('Consent changed');
// Check current consent state
if (OneTrust.IsAlertBoxClosedAndValid()) {
// User has given consent
loadConsentedScripts();
} else {
// User has not given consent
blockNonConsentedScripts();
}
});
// Listen for banner close events
OneTrust.OnAlertBoxClose(function() {
console.log('Banner closed');
// Handle banner close
});
// Listen for banner open events
OneTrust.OnAlertBoxOpen(function() {
console.log('Banner opened');
// Handle banner open
});
Custom Banner Implementation
Step 1: Disable Default Banner
-
OneTrust Admin Configuration
- Go to
Settings→Banner Settings - Disable "Show Default Banner"
- Save changes
- Go to
-
Custom Banner HTML
<div id="custom-consent-banner" class="custom-banner">
<div class="banner-content">
<h3>We value your privacy</h3>
<p>We use cookies and similar technologies to provide, protect, and improve our services.</p>
<div class="consent-options">
<button id="accept-all" class="btn btn-primary">Accept All</button>
<button id="reject-all" class="btn btn-secondary">Reject All</button>
<button id="customize" class="btn btn-outline">Customize</button>
</div>
<div class="banner-footer">
<a href="/privacy-policy">Privacy Policy</a>
<a href="/cookie-policy">Cookie Policy</a>
</div>
</div>
</div>
Step 2: Custom Banner Styling
.custom-banner {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: #fff;
border-top: 2px solid #007bff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
z-index: 9999;
padding: 20px;
}
.banner-content {
max-width: 1200px;
margin: 0 auto;
text-align: center;
}
.consent-options {
margin: 20px 0;
}
.btn {
padding: 10px 20px;
margin: 0 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-outline {
background: transparent;
color: #007bff;
border: 1px solid #007bff;
}
Step 3: Custom Banner JavaScript
// Custom banner functionality
document.addEventListener('DOMContentLoaded', function() {
const banner = document.getElementById('custom-consent-banner');
const acceptAllBtn = document.getElementById('accept-all');
const rejectAllBtn = document.getElementById('reject-all');
const customizeBtn = document.getElementById('customize');
// Show banner if no consent
if (!OneTrust.IsAlertBoxClosedAndValid()) {
banner.style.display = 'block';
}
// Accept all cookies
acceptAllBtn.addEventListener('click', function() {
OneTrust.AcceptAll();
banner.style.display = 'none';
loadAllScripts();
});
// Reject non-necessary cookies
rejectAllBtn.addEventListener('click', function() {
OneTrust.RejectAll();
banner.style.display = 'none';
loadOnlyNecessaryScripts();
});
// Show preference center
customizeBtn.addEventListener('click', function() {
OneTrust.ToggleInfoDisplay();
});
});
Custom Preference Center
Step 1: Create Custom Preference Center
<div id="custom-preference-center" class="preference-center" style={{
maxWidth: '600px',
height: 'auto',
borderRadius: '8px',
margin: '1rem 0',
display: 'block'
}}
display: 'none'
}}>
<div class="preference-content">
<h2>Cookie Preferences</h2>
<div class="preference-section">
<h3>Necessary Cookies</h3>
<p>These cookies are essential for the website to function properly.</p>
<div class="cookie-toggle">
<input type="checkbox" id="necessary" checked disabled>
<label for="necessary">Always Active</label>
</div>
</div>
<div class="preference-section">
<h3>Analytics Cookies</h3>
<p>These cookies help us understand how visitors interact with our website.</p>
<div class="cookie-toggle">
<input type="checkbox" id="analytics">
<label for="analytics">Analytics</label>
</div>
</div>
<div class="preference-section">
<h3>Marketing Cookies</h3>
<p>These cookies are used to deliver personalized advertisements.</p>
<div class="cookie-toggle">
<input type="checkbox" id="marketing">
<label for="marketing">Marketing</label>
</div>
</div>
<div class="preference-actions">
<button id="save-preferences" class="btn btn-primary">Save Preferences</button>
<button id="close-preferences" class="btn btn-secondary">Close</button>
</div>
</div>
</div>
Step 2: Preference Center Functionality
// Custom preference center functionality
function showPreferencenter() {
const preferencenter = document.getElementById('custom-preference-center');
preferencenter.style.display = 'block';
// Set current consent state
document.getElementById('analytics').checked = OneTrust.IsAlertBoxClosedAndValid('analytics');
document.getElementById('marketing').checked = OneTrust.IsAlertBoxClosedAndValid('marketing');
}
function hidePreferencenter() {
const preferencenter = document.getElementById('custom-preference-center');
preferencenter.style.display = 'none';
}
// Save preferences
document.getElementById('save-preferences').addEventListener('click', function() {
const analyticsConsent = document.getElementById('analytics').checked;
const marketingConsent = document.getElementById('marketing').checked;
// Update OneTrust consent
if (analyticsConsent) {
OneTrust.AcceptAnalytics();
} else {
OneTrust.RejectAnalytics();
}
if (marketingConsent) {
OneTrust.AcceptMarketing();
} else {
OneTrust.RejectMarketing();
}
// Hide preference center
hidePreferencenter();
// Reload scripts based on new consent
updateScripts();
});
// Close preference center
document.getElementById('close-preferences').addEventListener('click', function() {
hidePreferencenter();
});
Advanced Script Management
Step 1: Dynamic Script Loading
// Dynamic script loading based on consent
function loadScriptsBasedOnConsent() {
// Always load necessary scripts
loadNecessaryScripts();
// Load analytics scripts if consented
if (OneTrust.IsAlertBoxClosedAndValid('analytics')) {
loadAnalyticsScripts();
}
// Load marketing scripts if consented
if (OneTrust.IsAlertBoxClosedAndValid('marketing')) {
loadMarketingScripts();
}
}
function loadNecessaryScripts() {
// Load essential scripts
console.log('Loading necessary scripts');
}
function loadAnalyticsScripts() {
// Load Google Analytics
if (!window.gtag) {
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
script.async = true;
document.head.appendChild(script);
script.onload = function() {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
};
}
}
function loadMarketingScripts() {
// Load Facebook Pixel
if (!window.fbq) {
const script = document.createElement('script');
script.src = 'https://connect.facebook.net/en_US/fbevents.js';
script.async = true;
document.head.appendChild(script);
script.onload = function() {
window.fbq('init', 'PIXEL_ID');
window.fbq('track', 'PageView');
};
}
}
Step 2: Consent-Aware Script Execution
// Execute functions based on consent
function executeWithConsent(category, callback) {
if (OneTrust.IsAlertBoxClosedAndValid(category)) {
callback();
} else {
console.log(`Consent not given for ${category}`);
}
}
// Usage examples
executeWithConsent('analytics', function() {
// Track user interaction
gtag('event', 'button_click', {
'event_category': 'engagement',
'event_label': 'custom_button'
});
});
executeWithConsent('marketing', function() {
// Track conversion
fbq('track', 'Purchase', {
value: 100.00,
currency: 'USD'
});
});
Privacy Signal Integration
Step 1: Custom GPC Handling
// Custom GPC signal handling
function handleGPC() {
if (navigator.globalPrivacyControl) {
console.log('GPC signal detected');
// Override OneTrust consent for GPC
OneTrust.SetGPCStatus(true);
// Block non-necessary categories
blockAnalyticsScripts();
blockMarketingScripts();
// Show GPC notification
showGPCNotification();
}
}
function showGPCNotification() {
const notification = document.createElement('div');
notification.className = 'gpc-notification';
notification.innerHTML = `
<p>Global Privacy Control detected. Non-essential tracking has been disabled.</p>
<button onclick="this.parentElement.remove()">Dismiss</button>
`;
document.body.appendChild(notification);
}
Step 2: Custom DNT Handling
// Custom DNT signal handling
function handleDNT() {
const dnt = navigator.doNotTrack || window.doNotTrack;
if (dnt === "1" || dnt === "yes") {
console.log('DNT signal detected');
// Set OneTrust DNT status
OneTrust.SetDNTStatus(true);
// Apply enhanced privacy settings
applyEnhancedPrivacySettings();
}
}
function applyEnhancedPrivacySettings() {
// Block all non-necessary tracking
blockAllTrackingScripts();
// Show enhanced privacy mode
showEnhancedPrivacyMode();
}
Performance Optimization
Step 1: Lazy Loading
// Lazy load scripts based on user interaction
function setupLazyLoading() {
// Load analytics when user scrolls
let analyticsLoaded = false;
window.addEventListener('scroll', function() {
if (!analyticsLoaded && OneTrust.IsAlertBoxClosedAndValid('analytics')) {
loadAnalyticsScripts();
analyticsLoaded = true;
}
});
// Load marketing when user interacts
let marketingLoaded = false;
document.addEventListener('click', function() {
if (!marketingLoaded && OneTrust.IsAlertBoxClosedAndValid('marketing')) {
loadMarketingScripts();
marketingLoaded = true;
}
});
}
Step 2: Resource Management
// Manage script resources efficiently
class ScriptManager {
constructor() {
this.loadedScripts = new Set();
this.scriptQue = [];
}
loadScript(src, category) {
if (this.loadedScripts.has(src)) {
return Promise.resolve();
}
if (!OneTrust.IsAlertBoxClosedAndValid(category)) {
return Promise.reject('Consent not given');
}
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => {
this.loadedScripts.add(src);
resolve();
};
script.onerror = reject;
document.head.appendChild(script);
});
}
queScript(src, category) {
this.scriptQue.push({ src, category });
}
processQue() {
this.scriptQue.forEach(({ src, category }) => {
this.loadScript(src, category);
});
this.scriptQue = [];
}
}
// Usage
const scriptManager = new ScriptManager();
scriptManager.queScript('https://example.com/analytics.js', 'analytics');
scriptManager.queScript('https://example.com/marketing.js', 'marketing');
// Process que when consent is given
OneTrust.OnConsentChanged(function() {
scriptManager.processQue();
});
Testing and Validation
Step 1: Custom Testing Framework
// Custom testing framework for consent management
class ConsentTester {
constructor() {
this.tests = [];
this.results = [];
}
addTest(name, testFunction) {
this.tests.push({ name, testFunction });
}
async runTests() {
console.log('Running consent management tests...');
for (const test of this.tests) {
try {
const result = await test.testFunction();
this.results.push({ name: test.name, passed: true, result });
console.log(`✅ ${test.name}: PASSED`);
} catch (error) {
this.results.push({ name: test.name, passed: false, error: error.message });
console.log(`❌ ${test.name}: FAILED - ${error.message}`);
}
}
this.printResults();
}
printResults() {
const passed = this.results.filter(r => r.passed).length;
const total = this.results.length;
console.log(`\nTest Results: ${passed}/${total} tests passed`);
if (passed < total) {
console.log('\nFailed Tests:');
this.results.filter(r => !r.passed).forEach(r => {
console.log(`- ${r.name}: ${r.error}`);
});
}
}
}
// Example tests
const tester = new ConsentTester();
tester.addTest('Banner Display', async function() {
if (!OneTrust.IsAlertBoxClosedAndValid()) {
const banner = document.querySelector('.custom-banner');
return banner && banner.style.display !== 'none';
}
return true;
});
tester.addTest('Script Blocking', async function() {
// Test that scripts are blocked without consent
return !window.gtag && !window.fbq;
});
tester.addTest('Consent Persistence', async function() {
// Test that consent persists across page reloads
const consent = localStorage.getItem('OneTrustConsent');
return consent !== null;
});
// Run tests
tester.runTests();
Best Practices
1. Performance First
- Minimize blocking operations
- Use lazy loading for non-critical scripts
- Optimize script loading sequence
2. User Experience
- Provide clear consent options
- Show immediate feedback for user actions
- Maintain site functionality during consent process
3. Compliance
- Always respect user consent choices
- Implement privacy signals properly
- Maintain audit trails for consent
4. Testing
- Test thoroughly in multiple browsers
- Validate with privacy tools
- Monitor performance impact
Related Documentation
Rember: Custom implementations give you flexibility but also responsibility. Ensure your custom code maintains compliance and provides a good user experience.