engellna09/static-url-param-sync-example
0
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8" />5 <meta name="viewport" content="width=device-width" />6 <title>Static Space URL sync example</title>7 </head>8 <body>9 <div>10 <h2>Sync the query string and the hash to the parent page URL</h2>11 <label for="">12 Query string13 <input type="text" id="query">14 </label>15 <label>16 Hash17 <input type="text" id="hash">18 </label>19 <button onclick="sync()">Sync</button>20 </div>21 22 <div>23 <h2>Read the initial query and hash</h2>24 <label>25 Initial query26 <input type="text" readonly id="initial-query">27 </label>28 <label>29 Initial hash30 <input type="text" readonly id="initial-hash">31 </label>32 </div>33 34 <div>35 <h2>Read the hash reactively</h2>36 <input type="text" readonly id="read-hash-reactive">37 </div>38 39 <script>40 // Sync query and hash from this embedded app to the parent page URL.41 function sync() {42 const queryString = document.getElementById("query").value;43 const hash = document.getElementById("hash").value;44 45 // HF Spaces' spacial message type to update the query string and the hash in the parent page URL46 window.parent.postMessage({47 queryString,48 hash,49 }, "https://huggingface.co");50 }51 52 // Read the initial query and hash.53 const initialQuery = window.location.search;54 const initialHash = window.location.hash;55 document.getElementById("initial-query").value = initialQuery ?? "";56 document.getElementById("initial-hash").value = initialHash ?? "";57 58 // Read the updated hash reactively.59 // 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).60 window.addEventListener("hashchange", (event) => {61 console.log("hash change event", event);62 const currentHash = window.location.hash;63 document.getElementById("read-hash-reactive").value = currentHash;64 });65 </script>66 </body>67</html>68 