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:
- Detects
darkclass mutations ondocument.documentElementordocument.body. - Checks
localStorage.themeandprefers-color-scheme: dark. - Dispatches
tc-themeevents 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
themeparameter specified in the URL (?theme=lightor?theme=dark).