|
8 | 8 | return; |
9 | 9 | } |
10 | 10 |
|
| 11 | + const initialTheme = script.getAttribute("data-theme") || "light"; |
| 12 | + |
11 | 13 | // Known widget domain determined from script source or current origin |
12 | 14 | const scriptUrl = new URL(script.src); |
13 | 15 | const widgetHost = scriptUrl.origin; |
|
18 | 20 | container.style.overflow = "hidden"; |
19 | 21 |
|
20 | 22 | const iframe = document.createElement("iframe"); |
21 | | - iframe.src = `${widgetHost}/embed/${encodeURIComponent(widgetSlug)}`; |
| 23 | + const embedUrl = new URL(`${widgetHost}/embed/${encodeURIComponent(widgetSlug)}`); |
| 24 | + if (initialTheme) { |
| 25 | + embedUrl.searchParams.set("theme", initialTheme); |
| 26 | + } |
| 27 | + iframe.src = embedUrl.toString(); |
| 28 | + |
22 | 29 | // Strict sandboxing: allow-scripts, allow-same-origin, and allow-popups for verification page links |
23 | 30 | iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"); |
24 | 31 | iframe.style.width = "100%"; |
|
30 | 37 | container.appendChild(iframe); |
31 | 38 | script.parentNode.insertBefore(container, script.nextSibling); |
32 | 39 |
|
33 | | - // Listen strictly for auto-resize postMessage from widget domain |
| 40 | + // Listen for auto-resize postMessage from widget domain & host-page live theme updates |
34 | 41 | window.addEventListener("message", function (event) { |
35 | | - // Validate event.origin against the expected widget serving domain! |
36 | | - if (event.origin !== widgetHost) return; |
37 | | - |
38 | | - if (event.data && event.data.type === "clientecho-resize" && typeof event.data.height === "number") { |
| 42 | + // Resize message sent from iframe |
| 43 | + if (event.origin === widgetHost && event.data && event.data.type === "clientecho-resize" && typeof event.data.height === "number") { |
39 | 44 | iframe.style.height = `${Math.max(150, event.data.height)}px`; |
40 | 45 | } |
| 46 | + |
| 47 | + // Host page theme change notification (relay to iframe) |
| 48 | + if (event.data && event.data.type === "clientecho-set-theme" && typeof event.data.theme === "string") { |
| 49 | + if (iframe.contentWindow) { |
| 50 | + iframe.contentWindow.postMessage( |
| 51 | + { type: "clientecho-set-theme", theme: event.data.theme }, |
| 52 | + "*" |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
41 | 56 | }); |
42 | 57 | })(); |
| 58 | + |
0 commit comments