demo · v131
History-Aware Dialog
Use the toggle event fired by <dialog> to mirror open/closed state in the URL hash — so the Back button closes the dialog and sharing the URL re-opens it on load. Pure web-platform, no router library needed.
how to use
Open the dialog, then press the browser Back button — the dialog closes and the hash disappears from the URL. Or: copy the URL after opening (when the hash is visible) and open it in a new tab — the dialog opens automatically on load.
simulated URL bar
event log
—waiting for events…
the code
const dialog = document.querySelector("dialog");
const HASH = "#dialog-open";
// Mirror open → hash push, close → hash pop
dialog.addEventListener("toggle", (e) => {
if (e.newState === "open") {
history.pushState(null, "", HASH);
} else if (location.hash === HASH) {
history.back(); // remove hash entry from history
}
});
// Back button (or programmatic hash removal) closes dialog
window.addEventListener("hashchange", () => {
if (location.hash !== HASH && dialog.open) {
dialog.close();
}
});
// Deep-link: open on page load if hash is present
if (location.hash === HASH) dialog.showModal();
// Buttons
openBtn.onclick = () => dialog.showModal();
closeBtn.onclick = () => dialog.close();