From 2622dcd67b68ce7b78747dafda5bbaa4ba02ac85 Mon Sep 17 00:00:00 2001 From: Martin Othamar Date: Tue, 13 Aug 2024 13:09:02 +0200 Subject: [PATCH] Add 'base' element to 'head' to normalize relative urls/references (#2263) * Add 'base' element to 'head' to normalize relative urls/references * Try to format * Try to format * Prettier++ * Using document.head, wrapping closure to prevent global pollution (dunno if that happens anymore with all the preprocessing, but better to be safe) * Block-scoping instead of closure --------- Co-authored-by: Ole Martin Handeland --- src/features/baseurlinjection.ts | 17 +++++++++++++++++ src/index.tsx | 1 + 2 files changed, 18 insertions(+) create mode 100644 src/features/baseurlinjection.ts diff --git a/src/features/baseurlinjection.ts b/src/features/baseurlinjection.ts new file mode 100644 index 0000000000..b76784bd49 --- /dev/null +++ b/src/features/baseurlinjection.ts @@ -0,0 +1,17 @@ +// Apps are running in a subpath of `/{org}/{app}` both locally and in deployed environments +// some features make use of relative paths that should resolve relative to this subpath. +// * `image.src` on the `ImageComponent` might have `some-image.jpg` which we expect to then exist in the `wwwroot/` +// folder of the app. +// The `base` element in the HTML head will make relative references resolve from `base.href`. +// Bugreport: https://github.com/Altinn/app-frontend-react/issues/2257 +{ + const base = document.createElement('base'); + const { protocol, hostname, port: _port } = window.location; + const { org, app } = window; + const isDefaultHttpsPort = protocol === 'https:' && _port === '443'; + const isDefaultHttpPort = protocol === 'http:' && _port === '80'; + const isDefaultPort = isDefaultHttpsPort || isDefaultHttpPort; + const port = _port && !isDefaultPort ? `:${_port}` : ''; + base.href = `${protocol}//${hostname}${port}/${org}/${app}/`; + document.head.appendChild(base); +} diff --git a/src/index.tsx b/src/index.tsx index 66e77d3bec..96f9f6b886 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -7,6 +7,7 @@ import { createRoot } from 'react-dom/client'; import { createHashRouter, RouterProvider, ScrollRestoration } from 'react-router-dom'; import { Slide, ToastContainer } from 'react-toastify'; +import 'src/features/baseurlinjection'; import 'src/features/toggles'; import 'src/features/logging'; import 'src/features/styleInjection';