JavaScript API Reference
After the LegalBanner SDK loads, it exposes a global window.LegalBanner object that you can use to interact with the consent banner programmatically.
Get Current Consent State
``javascript
const consent = window.LegalBanner.getConsent()
// Returns:
// {
// essential: true, // always true
// functional: false,
// analytics: true,
// marketing: false
// }
// Returns null if no consent decision has been made yet
`
Listen for Consent Changes
`javascript
window.LegalBanner.onChange((state) => {
console.log('Consent updated:', state)
if (state.analytics) {
// Initialize Google Analytics
gtag('config', 'G-XXXXX')
}
if (state.marketing) {
// Initialize Facebook Pixel
fbq('init', '123456789')
}
})
`
The callback fires whenever the visitor updates their consent preferences.
Open Preferences Programmatically
`javascript
window.LegalBanner.openPreferences()
`
Use this to let visitors change their cookie preferences from a link in your footer:
`html
Cookie Settings
`
Script Activation Pattern
The recommended way to control third-party scripts is the activation pattern. Instead of loading scripts directly, mark them for category-based activation:
`html
`
How it works:
1.
type="text/plain" prevents the browser from executing the script
2. data-lb-category="analytics" tells LegalBanner which consent category controls it
3. When the visitor consents to "analytics", LegalBanner changes the type to text/javascript and the script executes
Inline Scripts
The same pattern works for inline scripts:
`html
`
Valid Category Values
Use these values for
data-lb-category:
essential — Always active (scripts run immediately)
functional — Enhanced features
analytics — Usage tracking
marketing — Advertising and retargeting
Waiting for SDK Ready
If you need to check consent before the SDK has loaded:
`javascript
if (window.LegalBanner) {
// SDK already loaded
const consent = window.LegalBanner.getConsent()
} else {
// Wait for SDK
window.addEventListener('lb:ready', () => {
const consent = window.LegalBanner.getConsent()
})
}
``