Skip to content

Commit

Permalink
Add 'base' element to 'head' to normalize relative urls/references (#…
Browse files Browse the repository at this point in the history
…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 <[email protected]>
  • Loading branch information
martinothamar and Ole Martin Handeland authored Aug 13, 2024
1 parent ab2a4f8 commit 2622dcd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/features/baseurlinjection.ts
Original file line number Diff line number Diff line change
@@ -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);
}
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down

0 comments on commit 2622dcd

Please sign in to comment.