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';