Consent API
Programmatic control over the consent banner and consent state via JavaScript.
Global Object
Once the Cookiewise script loads, a global window.Cookiewise object is available with the following methods:
Cookiewise.showBanner()
Programmatically display the consent banner, even if the user has already consented.
Cookiewise.showBanner();Cookiewise.hideBanner()
Hide the consent banner without recording a consent event.
Cookiewise.hideBanner();Cookiewise.getConsent()
Returns Object
Returns the current consent state.
const consent = Cookiewise.getConsent();
// Returns:
// {
// categories: { necessary: true, functional: false, analytics: true, marketing: false, social: false },
// timestamp: "2025-03-01T12:00:00Z",
// method: "custom"
// }Cookiewise.updateConsent(categories)
Programmatically update consent preferences. Triggers a new consent record.
Cookiewise.updateConsent({
necessary: true, // always true, cannot be false
functional: true,
analytics: true,
marketing: false,
social: false
});Cookiewise.openSettings()
Open the cookie settings modal where users can toggle individual categories.
document.querySelector('#cookie-settings-btn').addEventListener('click', () => Cookiewise.openSettings());Cookiewise.hasConsent(category)
Returns Boolean
Check if a specific category has been consented to. Useful for conditional script loading.
if (Cookiewise.hasConsent('analytics')) {
// Safe to initialize Google Analytics
gtag('config', 'GA_MEASUREMENT_ID');
}Events
Cookiewise dispatches custom events on the window object that you can listen for:
cookiewise-ready
Fired when Cookiewise has finished initializing and is ready for interaction.
window.addEventListener('cookiewise-ready', (e) => {
console.log('Cookiewise initialized', e.detail);
});cookiewise-consent-updated
Fired whenever the user updates their consent preferences (accept, reject, or custom).
window.addEventListener('cookiewise-consent-updated', (e) => {
const { categories, method, timestamp } = e.detail;
if (categories.analytics) {
// Initialize analytics
}
if (categories.marketing) {
// Initialize marketing pixels
}
});Conditional Script Loading Pattern
The recommended pattern for loading third-party scripts based on consent:
window.addEventListener('cookiewise-consent-updated', (e) => {
const { categories } = e.detail;
// Google Analytics
if (categories.analytics && !window._gaLoaded) {
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXX';
document.head.appendChild(script);
window._gaLoaded = true;
}
// Facebook Pixel
if (categories.marketing && !window._fbLoaded) {
// Initialize Facebook Pixel
window._fbLoaded = true;
}
});