Skip to main content

Script Manager

The Script Manager enables you to load and manage scripts that inject cookies in compliance with privacy regulations such as GDPR, CCPA, and similar data protection laws. Any scripts or custom apps that set cookies requiring explicit user consent must be registered through window.BM.scriptManager.

Overview

The Script Manager automatically handles loading and unloading scripts based on user consent preferences, ensuring compliance with privacy regulations.

Important

Without a consent management app installed (e.g., Bettermode's Cookie Consent Management Integration), the Script Manager cannot access user consent preferences and will load all registered scripts by default.

Script Definition

Scripts are defined using the following interface:

type Script = {
/**
* Unique identifier for the script
*/
name: string;

/**
* Cookie consent category that determines when the script can run
*/
consentCategory: CookieCategory;

/**
* Function called when user grants consent for this category
*/
load?: () => void;

/**
* Function called when user revokes consent for this category
* If getCookiesToRemove is provided, cookies will be automatically cleaned up
*/
unload?: () => void;

/**
* Returns list of cookies to remove when consent is revoked
*
* @param params - Configuration object containing network location details
* @param params.domain - The domain of the network (e.g., "example.com")
* @param params.path - Optional sub-path where the network is hosted (e.g., "/community")
*
* @example
* // For a community hosted at https://example.com/community:
* // - domain: "example.com"
* // - path: "/community"
* //
* // For a community hosted at https://mycommunity.com:
* // - domain: "mycommunity.com"
* // - path: "" (empty string)
*
* @returns Array of cookie definitions to remove
*/
getCookiesToRemove?: (params: {
domain: string;
path?: string;
}) => Array<{
name: string;
options?: {
domain?: string;
path?: string;
secure?: boolean;
sameSite?: 'strict' | 'lax' | 'none';
};
}>;
};

Script Lifecycle

The Script Manager follows a well-defined lifecycle to ensure proper consent handling and privacy compliance:

1. Registration Phase

  • Script is registered in the Script Manager
  • No execution occurs until consent is determined
  • Script Manager evaluates existing user consent preferences
  • Scripts with granted consent categories execute their load() function immediately
  • Scripts without consent remain inactive

When users modify their cookie preferences:

Consent Granted:

  • Script's load() function is executed
  • Script can now set cookies and perform its functionality

Consent Revoked:

  • Script's unload() function is called for cleanup
  • If getCookiesToRemove() is provided, cookies are automatically removed
  • Script should stop any ongoing activities

4. Cleanup Phase

  • Occurs when consent is revoked
  • All associated cookies are removed according to the removal specification

This implementation ensures your scripts comply with privacy regulations while providing a smooth user experience.

Registration Process

1. Wait for Initialization

The Script Manager must be fully initialized before registering scripts. Listen for the ready event:

window.BM.on('ready', () => {
// Script Manager is ready - register your scripts here
});

2. Register Your Script

Register your script by calling window.BM.scriptManager.register() with your script configuration. The following example demonstrates how to integrate Microsoft Clarity analytics with proper consent handling:

window.BM.on('ready', () => {
window.BM.scriptManager.register({
name: 'ms-clarity',
consentCategory: 'analytics',
load: () => {
// Initialize Microsoft Clarity when consent is granted
// Reference: https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-setup
const clarity = function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
}

// Initialize Clarity if not already loaded
if (!window.clarity) {
clarity(window, document, "clarity", "script", "<PROJECT_ID>");
}

// Start tracking with user consent
window.clarity('consent')
window.clarity('start')
},
unload: () => {
// Stop tracking when consent is revoked
if (window.clarity) {
window.clarity('consent', false)
window.clarity('stop')
}
},
getCookiesToRemove: ({ domain, path = '/' }) => {
// Calculate proper domain for cookie removal
const getCookieOptions = () => {
try {
const domainParts = domain.split('.')
// Microsoft clarity sets cookies on the highest domain level.
const removalDomain = `${domainParts.slice(-2).join('.')}`
return { domain: removalDomain, path }
} catch {
// Fallback to current hostname
return { domain: window.location.hostname, path }
}
}
// Microsoft Clarity automatically clears cookie values when consent is revoked,
// but converts them to session cookies. For full GDPR compliance, we manually
// remove the cookies entirely.
// Reference: https://github.com/microsoft/clarity/issues/211#issuecomment-2056602230
const options = getCookieOptions()

return [
{ name: '_clck', options },
{ name: '_clsk', options },
]
},
});
});

Proper cookie removal when consent is revoked is essential for privacy compliance. Most third-party scripts provide built-in methods for consent management and cookie cleanup. We recommend using these official APIs whenever possible, with the Script Manager's getCookiesToRemove function serving as additional cleanup for edge cases, as mentioned in the example above.

Recommended Approach
  1. Use Official APIs First: Leverage the script's built-in consent management (e.g., window.clarity('consent', false))
  2. Manual Cleanup: Use getCookiesToRemove for complete cookie removal when the official API is insufficient
  3. Test Thoroughly: Verify cookie removal in different environments and domain configurations

Important Considerations

  • Proper Attribute Matching: Browsers require properly matching of cookie attributes (domain, path, secure, sameSite) for successful removal
  • Cookie Prefixes: Understand browser cookie mechanics including cookie prefixes and more
  • Domain Variations: Different scripts may set cookies on various domain levels (current hostname vs. root domain)

Most scripts set cookies on the current domain (window.location.hostname), but some third-party services use different strategies:

Cookie StrategyExample DomainCookie DomainRemoval Domain
Current hostnameapp.example.comapp.example.comwindow.location.hostname
Subdomain wildcardapp.example.com.example.com.example.com
Specific pathapp.example.com/adminapp.example.com/adminwindow.location.hostname with path: '/admin'

Most scripts set cookies on the current hostname:

getCookiesToRemove: ({ domain, path }) => [
{
name: 'analytics-session',
options: { domain: window.location.hostname }
}
]

Analytics tools often set cookies on the root domain for cross-subdomain tracking:

getCookiesToRemove: ({ domain, path }) => [
{
name: '_clck', // Microsoft Clarity cookie
options: { domain: `.${domain}` } // Leading dot for root domain
}
]

Cookies restricted to specific application paths:

getCookiesToRemove: ({ domain, path }) => [
{
name: 'admin-session',
options: {
domain: window.location.hostname,
path: '/admin'
}
}
]

Cookies with security attributes for HTTPS environments:

getCookiesToRemove: ({ domain, path }) => [
{
name: 'secure-tracking',
options: {
domain: `.${domain}`,
path: '/',
secure: true,
sameSite: 'none'
}
}
]
Third-Party Cookie Management

Many third-party scripts (e.g., Google Analytics, Microsoft Clarity, Facebook Pixel) set cookies on their own domains, which cannot be removed directly through your application's cookie removal mechanism.

Important considerations:

  • Cross-domain limitations: JavaScript can only remove cookies from the current domain
  • SDK-specific cleanup: Check the script's official SDK for consent revocation methods
  • Manual intervention required: Some services require explicit API calls to clear tracking data

If cookies are not being removed successfully:

  1. Inspect Cookie Attributes: Use browser DevTools (Application → Cookies) to examine how cookies are set
  2. Verify Attribute Matching: Ensure all cookie attributes in your removal configuration match
  3. Test Across Environments: Validate cookie removal in development, staging, and production environments
  4. Check Console Errors: Monitor for any JavaScript errors during the removal process
DevTools Inspection

Navigate to DevTools → Application → Cookies to view all cookie attributes. Copy the domain, path, secure, and sameSite values for accurate removal configuration.