File size: 1,975 Bytes
76e276e
 
 
 
 
dde26cd
76e276e
 
9f854a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde26cd
 
904843c
dde26cd
 
 
 
 
 
 
 
b9c5a8f
dde26cd
9f854a8
904843c
9f854a8
 
 
 
 
904843c
 
9f854a8
 
 
 
 
dde26cd
76e276e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!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>