Advanced Consent Scenarios and Edge Cases

Real-world cookie consent implementation involves numerous edge cases and complex scenarios. Single sign-on (SSO) systems require coordinating consent across multiple domains. Progressive web applications need consent for service workers and push notifications. Embedded widgets like YouTube videos or social media feeds require careful handling to prevent unauthorized cookie setting.

Cross-domain consent synchronization presents particular challenges. When users interact with multiple properties owned by the same organization, maintaining consistent consent preferences enhances user experience while ensuring compliance. This requires secure communication mechanisms between domains while respecting browser security restrictions.

// Cross-domain consent synchronization
class ConsentSynchronizer {
  constructor() {
    this.syncEndpoint = 'https://consent.example.com/sync';
    this.allowedDomains = ['example.com', 'shop.example.com', 'blog.example.com'];
  }

  // Synchronize consent across domains
  async syncConsent(consentData) {
    // Create secure message
    const message = {
      type: 'consent-sync',
      consent: consentData,
      timestamp: new Date().toISOString(),
      origin: window.location.origin,
      signature: await this.signMessage(consentData)
    };
    
    // Send to other domains via postMessage
    this.allowedDomains.forEach(domain => {
      if (domain !== window.location.hostname) {
        const iframe = this.createSyncIframe(domain);
        iframe.onload = () => {
          iframe.contentWindow.postMessage(message, `https://${domain}`);
        };
      }
    });
    
    // Also sync via backend for reliability
    await this.syncViaBackend(message);
  }

  // Listen for consent updates from other domains
  listenForUpdates() {
    window.addEventListener('message', async (event) => {
      // Verify origin
      if (!this.isAllowedOrigin(event.origin)) return;
      
      // Verify message type
      if (event.data.type !== 'consent-sync') return;
      
      // Verify signature
      if (!await this.verifySignature(event.data)) return;
      
      // Apply consent update
      cookieConsent.applyExternalConsent(event.data.consent);
    });
  }
}