Skip to content

Instantly share code, notes, and snippets.

@mattiaz9
Created May 17, 2020 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattiaz9/3a56fd4b03aa8f45572a958e5560ac2c to your computer and use it in GitHub Desktop.
Save mattiaz9/3a56fd4b03aa8f45572a958e5560ac2c to your computer and use it in GitHub Desktop.
Fix URLs of a react app deployed on Swarm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/images/icon.png" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/images/icon-192.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script>
var path = window.location.pathname;
var bzzPattern = /\/bzz:\/([^/]+)/;
window.__basename__ = bzzPattern.test(window.location.pathname)
? window.location.pathname.match(bzzPattern)[0]
: '';
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- Fix relative paths -->
<script>
(function () {
var observer = new MutationObserver(mutations => {
mutations.map(mutation => {
var nodes = Array.from(mutation.addedNodes).filter(node => node.tagName === "SCRIPT" || node.tagName === "LINK");
fixUrls(nodes);
});
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: false
});
var currentScripts = document.querySelectorAll('script');
fixUrls(currentScripts);
var currentLinks = document.querySelectorAll('link');
fixUrls(currentLinks);
function fixUrls(nodes) {
nodes.forEach(function (node) {
if (node.tagName === "SCRIPT" && /__basename__/g.test(node.innerText)) {
var copy = node.cloneNode(true);
copy.innerText = node.innerText.replace(/__basename__/g, window.__basename__);
node.parentNode.appendChild(copy);
node.remove();
} else {
var href = node.getAttribute('href');
if (href && /__basename__/.test(href)) {
var copy = node.cloneNode(true);
copy.href = href.replace(/__basename__/g, window.__basename__);
node.parentNode.appendChild(copy);
node.remove();
}
var src = node.getAttribute('src');
if (src && /__basename__/.test(src)) {
var copy = node.cloneNode(true);
copy.src = src.replace(/__basename__/g, window.__basename__);
node.parentNode.appendChild(copy);
node.remove();
}
}
});
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment