Osano JavaScript API Demo
This page demonstrates how to use the Osano JavaScript API to dynamically update page content based on user consent preferences.
The page background will change color based on your consent choices:
- Green tint: All non-essential categories accepted
- Red tint: All non-essential categories denied
- Yellow tint: Mixed acceptance of non-essential categories
Try changing your cookie preferences using the link below to see how the page responds in real-time!
Thanks for accepting all categories! Here's a happy puppy!

How It Works
This page demonstrates practical implementation of the Osano JavaScript API for responsive content based on user privacy choices. Here's exactly what's happening behind the scenes:
1. Initial Consent Detection
When the page loads, the osano-cm-initialized
event listener captures the current consent state using Osano.cm.getConsent()
and immediately applies the appropriate styling.
2. Real-time Preference Tracking
The page listens for two critical events:
osano-cm-consent-changed
: Triggered whenever a specific consent category changes state (Accept/Deny)osano-cm-consent-saved
: Triggered when the user finalizes their consent choices
3. Dynamic Content Adjustment
The updatePageBasedOnConsent()
function processes the consent object, which looks like:
{
ANALYTICS: "ACCEPT"|"DENY",
MARKETING: "ACCEPT"|"DENY",
PERSONALIZATION: "ACCEPT"|"DENY",
ESSENTIAL: "ACCEPT",
OPT-OUT: "ACCEPT"|"DENY",
STORAGE: "ACCEPT"|"DENY"
}
Based on the status of non-essential categories, the page updates its appearance and text content in real-time.
Implementation Guide
Want to implement similar consent-based dynamic content on your website? Expand the section below for a complete guide:
Step-by-Step Implementation Guide
Step 1: Add Osano to Your Website
First, add the Osano cookie consent script to your website:
<script src="https://cmp.osano.com/[YOUR_ACCOUNT_ID]/[YOUR_CUSTOMER_ID]/osano.js"></script>
Note: Replace placeholders with your unique Osano IDs.
Step 2: Create Your Base CSS Styles
Add these CSS styles to your stylesheet to create visual indicators for consent status. These styles provide a foundation for showing/hiding content and creating visual feedback for users:
/* Consent status indicators */
.consent-status {
margin: 2rem 0;
padding: 1.5rem;
border-radius: 8px;
background-color: #f5f5f5;
transition: background-color 0.5s ease;
}
.status-accepted {
color: #2a9d4e;
font-weight: 600;
}
.status-denied {
color: #d32f2f;
font-weight: 600;
}
/* Conditional content container */
.conditional-content {
display: none; /* Hidden by default */
}
/* Style for consent-required messages */
.consent-required-message {
padding: 1rem;
background-color: #f8f9fa;
border-radius: 4px;
margin: 1rem 0;
text-align: center;
}
.consent-required-message a {
color: var(--electric-indigo);
text-decoration: underline;
font-weight: 500;
}
Step 3: Add HTML Structure
Set up your HTML structure to display consent status and conditional content. This example shows how to create both a consent status display and conditional content sections that require specific consent categories:
<!-- Consent Status Display -->
<div class="consent-status" id="consent-status">
<h3>Your Current Consent Status</h3>
<p id="consent-summary">Checking your consent preferences...</p>
<div class="consent-category">
<span>Analytics:</span>
<span id="analytics-status">Loading...</span>
</div>
<div class="consent-category">
<span>Marketing:</span>
<span id="marketing-status">Loading...</span>
</div>
<div class="consent-category">
<span>Personalization:</span>
<span id="personalization-status">Loading...</span>
</div>
</div>
<!-- Example of conditional content with consent message -->
<div class="conditional-content" id="personalized-video">
<h3>Personalized Video Content</h3>
<video controls>
<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
<!-- Consent required message (shown when content is hidden) -->
<div class="consent-required-message" id="personalized-video-message">
<p>Enable Personalization in your <a href="javascript:void(0)" onclick="Osano.cm.showDrawer()">Cookie Preferences</a> to view this video content.</p>
</div>
<!-- Button to Open Cookie Preferences -->
<button onclick="Osano.cm.showDrawer()" class="preferences-button">Open Cookie Preferences</button>
Step 4: Implement the JavaScript Logic
Add this JavaScript to your page to handle consent changes. This code demonstrates how to show/hide content and display appropriate messages based on user consent:
// Function to update the page based on consent status
function updatePageBasedOnConsent(consent) {
if (!consent) return;
// Define which categories you want to track
const nonEssentialCategories = ['ANALYTICS', 'MARKETING', 'PERSONALIZATION'];
const statusElements = {
'ANALYTICS': document.getElementById('analytics-status'),
'MARKETING': document.getElementById('marketing-status'),
'PERSONALIZATION': document.getElementById('personalization-status')
};
// Update individual category status displays
nonEssentialCategories.forEach(category => {
const status = consent[category];
if (statusElements[category]) {
statusElements[category].textContent = status;
statusElements[category].className = status === 'ACCEPT' ? 'status-accepted' : 'status-denied';
}
});
// Handle conditional content visibility
const personalizedVideo = document.getElementById('personalized-video');
const personalizedVideoMessage = document.getElementById('personalized-video-message');
if (personalizedVideo && personalizedVideoMessage) {
if (consent.PERSONALIZATION === 'ACCEPT') {
personalizedVideo.style.display = 'block';
personalizedVideoMessage.style.display = 'none';
} else {
personalizedVideo.style.display = 'none';
personalizedVideoMessage.style.display = 'block';
}
}
}
// Wait for Osano to initialize
document.addEventListener('DOMContentLoaded', function() {
if (typeof Osano !== 'undefined' && Osano.cm) {
// Initialize when Osano is ready
Osano.cm.addEventListener('osano-cm-initialized', function(consent) {
console.log('Osano initialized with consent:', consent);
updatePageBasedOnConsent(consent);
});
// Update when consent is saved
Osano.cm.addEventListener('osano-cm-consent-saved', function(consent) {
console.log('Consent saved:', consent);
updatePageBasedOnConsent(consent);
});
} else {
console.error('Osano script not loaded properly');
}
});
Step 5: Advanced Customization
Here are some additional customization options for different use cases:
A. Add Personalized UI Elements
// Example: Show different hero images based on consent
function updateHeroImage(consent) {
const hero = document.querySelector('.hero');
if (!hero) return;
if (consent.PERSONALIZATION === 'ACCEPT') {
// Load personalized hero image
hero.style.backgroundImage = 'url("personalized-hero.jpg")';
} else {
// Load generic hero image
hero.style.backgroundImage = 'url("default-hero.jpg")';
}
}
B. Dynamic Feature Activation
// Example: Enable chat widget based on marketing consent
function toggleChatWidget(consent) {
const chatWidget = document.getElementById('chat-widget');
const chatMessage = document.getElementById('chat-message');
if (!chatWidget || !chatMessage) return;
if (consent.MARKETING === 'ACCEPT') {
chatWidget.style.display = 'block';
chatMessage.style.display = 'none';
initializeChat(); // Your function to start the chat widget
} else {
chatWidget.style.display = 'none';
chatMessage.style.display = 'block';
chatMessage.innerHTML = 'Enable Marketing cookies in your <a href="javascript:void(0)" onclick="Osano.cm.showDrawer()">Cookie Preferences</a> to access live chat support.';
}
}
Step 6: Best Practices
- Clear Communication: Always explain why certain content or features require specific consent categories. Use clear, user-friendly language in consent-required messages.
- Graceful Degradation: Ensure your site remains functional and provides value even when users deny non-essential cookies. Never hide critical content or features behind consent walls.
- Performance Optimization: Avoid making expensive DOM operations on every consent change. Batch updates when possible and use efficient selectors.
- Accessibility: Ensure consent-required messages and conditional content are accessible to screen readers. Use proper ARIA attributes and maintain keyboard navigation.
- User Experience: Make it easy for users to update their preferences. Include clear calls-to-action and maintain consistent styling for preference-related UI elements.
- Testing: Test your implementation across different browsers and devices. Verify that content visibility changes correctly when consent is updated.
- Security: Never store or process personal data without proper consent. Implement proper data handling practices and respect user privacy choices.
- Documentation: Maintain clear documentation of which features require which consent categories. This helps with maintenance and ensures compliance.