The way around this is to grab the HTML server side, add a <base href="..." />
so any relative and absolute paths still work.
Here's my node route
/api/url/:url
export default async function handler(req, res) {
const url = `https://${req.query.url}`;
const response = await fetch(url);
const urlContents = await response.text();
// Prepend the base to make sure all relative and absolute paths work
const urlContentsWithHead = `<base href='${url}' /></head>${urlContents}`;
res.status(200).send(urlContentsWithHead);
}
You can then use this route directly in the iframe
<iframe src={`/api/url/${url}`} />
Oddly when I tried to do this "properly" by putting the <base />
element just before the closing </head>
tag by using a replace, it didn't work. But putting the base before all of the markup (even the <html>
) seemed to work.
Not sure if there will be any adverse affects 🤷