Skip to content

Instantly share code, notes, and snippets.

@pragmasoft-ua
Created July 21, 2023 15:23
Show Gist options
  • Save pragmasoft-ua/4fab84f5888a6e8277620666cce7dc22 to your computer and use it in GitHub Desktop.
Save pragmasoft-ua/4fab84f5888a6e8277620666cce7dc22 to your computer and use it in GitHub Desktop.
dialog deep linking
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dialog demo</title>
<script type="module">
/**
* @param url URL | Location
* @returns HTMLDialogElement | undefined
*/
function currentDialog(url) {
const id = url.hash.substring(1);
if (id) {
const el = document.getElementById(id);
if (el && el instanceof HTMLDialogElement) {
return el;
}
}
}
function resetHash() {
document.location.hash = "";
}
/**
* @param HTMLDialogElement | undefined | null
*/
function showDialog(dialog) {
if (dialog) {
dialog.onclose = resetHash;
dialog.showModal();
}
}
onhashchange = (e) => {
let url = new URL(e.oldURL);
currentDialog(url)?.close();
url = new URL(e.newURL);
showDialog(currentDialog(url));
};
showDialog(currentDialog(document.location));
</script>
</head>
<body>
<h1>Dialog demo</h1>
<dialog id="dialog">
<form method="dialog">
<p>Hi, I'm a dialog.</p>
<button autofocus>Cancel</button>
<button>Close</button>
</form>
</dialog>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment