TC
The Comparator
Academy Wiki / Technical Architecture

Theme Syncing & Responsive iFrames

Technical documentation on widget.js: postMessage API dark mode detection and dynamic height auto-resizing.

Theme Syncing & Responsive iFrame Architecture

To ensure widgets blend seamlessly into host publisher websites without scrollbars or color mismatch, The Comparator uses assets/js/widget.js.


1. How Theme Synchronization Works

Host websites often switch between Light and Dark modes. The embedded widget listens for theme changes on the parent window using the HTML5 postMessage API.

[Host Website (Parent)] โ”€โ”€ postMessage({ type: 'tc-theme', theme: 'dark' }) โ”€โ”€> [Comparator Widget (iFrame)]

Parent Host Script Setup

Add the lightweight widget.js script to your page footer:

<script src="https://thecomparator.tech/assets/js/widget.js" async></script>

This script automatically:

  1. Detects dark class mutations on document.documentElement or document.body.
  2. Checks localStorage.theme and prefers-color-scheme: dark.
  3. Dispatches tc-theme events to all active Comparator iFrames on the page.

2. Dynamic Height Auto-Resizing

To prevent vertical scrollbars inside the iFrame, the widget calculates its content scroll height dynamically and notifies the parent window:

// Example inside widget.js listener
window.addEventListener('message', function(event) {
    if (event.data && event.data.type === 'tc-resize') {
        const iframe = document.querySelector(`iframe[src*="${event.data.widgetId}"]`);
        if (iframe) {
            iframe.style.height = event.data.height + 'px';
        }
    }
});

3. Fallback Without JavaScript

If the host site disables JavaScript:

  • The iFrame falls back to the default height="450" specified in HTML.
  • The theme defaults to the theme parameter specified in the URL (?theme=light or ?theme=dark).