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

URL
event log
waiting for events…

Share This View

This dialog is part of the page's URL state. While it is open, #dialog-open appears in the address bar. Copy that URL and open it in any tab — the dialog is already open, no click required.

Press the browser Back button to close this dialog without touching the Close button. The toggle event removes the hash entry from history when the dialog closes, keeping things tidy.

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();

see also