whitphx's picture
whitphx HF staff
Update comment
904843c
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Static Space URL sync example</title>
</head>
<body>
<div>
<h2>Sync the query string and the hash to the parent page URL</h2>
<label for="">
Query string
<input type="text" id="query">
</label>
<label>
Hash
<input type="text" id="hash">
</label>
<button onclick="sync()">Sync</button>
</div>
<div>
<h2>Read the initial query and hash</h2>
<label>
Initial query
<input type="text" readonly id="initial-query">
</label>
<label>
Initial hash
<input type="text" readonly id="initial-hash">
</label>
</div>
<div>
<h2>Read the hash reactively</h2>
<input type="text" readonly id="read-hash-reactive">
</div>
<script>
// Sync query and hash from this embedded app to the parent page URL.
function sync() {
const queryString = document.getElementById("query").value;
const hash = document.getElementById("hash").value;
// HF Spaces' spacial message type to update the query string and the hash in the parent page URL
window.parent.postMessage({
queryString,
hash,
}, "https://huggingface.co");
}
// Read the initial query and hash.
const initialQuery = window.location.search;
const initialHash = window.location.hash;
document.getElementById("initial-query").value = initialQuery ?? "";
document.getElementById("initial-hash").value = initialHash ?? "";
// Read the updated hash reactively.
// Note: there is no way to capture the query string update like this because updating query string causes page-reload (ref: https://stackoverflow.com/a/4291024).
window.addEventListener("hashchange", (event) => {
console.log("hash change event", event);
const currentHash = window.location.hash;
document.getElementById("read-hash-reactive").value = currentHash;
});
</script>
</body>
</html>