Created
April 15, 2024 07:13
-
-
Save ykrods/89a43a3e55682128ab07b82a2ecf94c9 to your computer and use it in GitHub Desktop.
historyベースルータの最小実装的なもの
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"/> | |
<title>history iframe</title> | |
<script> | |
let page = window.location.pathname; | |
function updateContent(path) { | |
console.log(`history.length: ${window.history.length}`); | |
page = path; | |
const content = document.querySelector("#content"); | |
const routes = { | |
"/": () => { | |
document.title = "top"; | |
content.innerHTML = "top"; | |
}, | |
"/sub/(?<name>.+)": (params) => { | |
document.title = `sub/${params.name}`; | |
let iframe = content.querySelector("iframe") | |
if (!iframe) { | |
iframe = document.createElement("iframe"); | |
content.appendChild(iframe); | |
} | |
iframe.src = `/sub${params.name}.html`; | |
}, | |
".*": () => { | |
document.title = "not found"; | |
content.innerHTML = "not found"; | |
}, | |
} | |
for (const key of Object.keys(routes)) { | |
const re = new RegExp(`^${key}$`, 'i'); | |
const match = page.match(re); | |
if (match) { | |
routes[key](match.groups) | |
break; | |
} | |
}; | |
} | |
document.addEventListener("DOMContentLoaded", () => { | |
window.addEventListener("popstate", (evt) => { | |
updateContent(window.location.pathname); | |
}); | |
updateContent(window.location.pathname); | |
document.querySelectorAll("a").forEach((a) => { | |
a.addEventListener("click", (evt) => { | |
evt.preventDefault(); | |
window.history.pushState(null, '', a.href); | |
updateContent(window.location.pathname); | |
}); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<div> | |
<ul> | |
<li><a href="/">top</a></li> | |
<li><a href="/sub/1">/sub/1</a></li> | |
<li><a href="/sub/2">/sub/2</a></li> | |
</ul> | |
</div> | |
<div id="content"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment