diff --git a/apps/web/src/runtime/srcdoc.ts b/apps/web/src/runtime/srcdoc.ts index 0868c79a6..07946b32d 100644 --- a/apps/web/src/runtime/srcdoc.ts +++ b/apps/web/src/runtime/srcdoc.ts @@ -105,13 +105,39 @@ function injectManualEditBridge(doc: string): string { } function injectBeforeHeadEnd(doc: string, payload: string): string { - if (/<\/head>/i.test(doc)) return doc.replace(/<\/head>/i, `${payload}`); + if (typeof DOMParser !== 'undefined') { + try { + const parsed = new DOMParser().parseFromString(doc, 'text/html'); + if (parsed.head) parsed.head.insertAdjacentHTML('beforeend', payload); + return serializeHtmlDocument(parsed); + } catch { /* DOMParser failed; fall through to string path */ } + } + // String fallback: find the real (last one before
) + // to skip literals inside `; - if (/<\/body>/i.test(doc)) - return doc.replace(/<\/body>/i, `${script}