From a8bf1ab868b2a74e99702e6c3a04325e8c97f023 Mon Sep 17 00:00:00 2001 From: Sage Abdullah Date: Tue, 23 Jan 2024 18:48:35 +0000 Subject: [PATCH] Run scripts inside teleported element in TeleportController --- client/src/controllers/TeleportController.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/client/src/controllers/TeleportController.ts b/client/src/controllers/TeleportController.ts index c484c29e3f..ff9d126025 100644 --- a/client/src/controllers/TeleportController.ts +++ b/client/src/controllers/TeleportController.ts @@ -98,6 +98,22 @@ export class TeleportController extends Controller { throw new Error('Invalid template content.'); } + // HACK: + // cloneNode doesn't run scripts, so we need to create new script elements + // and copy the attributes and innerHTML over. This is necessary when we're + // teleporting a template that contains legacy init code, e.g. initDateChooser. + // Only do this for inline scripts, as that's what we're expecting. + templateElement + .querySelectorAll('script:not([src], [type])') + .forEach((script) => { + const newScript = document.createElement('script'); + Array.from(script.attributes).forEach((key) => + newScript.setAttribute(key.nodeName, key.nodeValue || ''), + ); + newScript.innerHTML = script.innerHTML; + script.replaceWith(newScript); + }); + return templateElement; } }