-
Notifications
You must be signed in to change notification settings - Fork 44
/
sync-location-hashes.js
56 lines (50 loc) · 1.94 KB
/
sync-location-hashes.js
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
// Watches for hash-changes on the given windows (i.e. frames), updating the
// others whenever one of them changes.
//
// Parameters:
// - windows: an Array of Windows.
// - initial (optional): the window whose hash is used to sync them initially.
// Returns a function that disables synchronisation again.
export default function syncLocationHashes(windows, { initial } = {}) {
const listeners = windows.map(win => function syncHashListener() {
syncHashToOthers(win)
})
function syncHashToOthers(win) {
// Read the window's hash, dropping the '#' if present.
let hash = win.location.hash
if (hash.startsWith('#')) {
hash = hash.substring(1)
}
// Likewise read each other window's hash, and update them where needed.
windows.forEach(otherWindow => {
if (otherWindow !== win) {
let otherHash = otherWindow.location.hash
if (otherHash.startsWith('#')) {
otherHash = otherHash.substring(1)
}
// Setting a window's location hash will trigger its hashchange event, which could
// then cause us to start syncing it back to the others again, etcetera. To avoid
// creating such an infinite loop, we simply ensure that a hash will not be set if
// it already has the right value.
if (otherHash !== hash) {
otherWindow.location.hash = hash
}
}
})
}
function enableAllListeners() {
windows.forEach((win, i) => {
win.addEventListener('hashchange', listeners[i])
})
}
function disableAllListeners() {
windows.forEach((win, i) => {
win.removeEventListener('hashchange', listeners[i])
})
}
if (initial !== undefined) {
syncHashToOthers(initial)
}
enableAllListeners()
return disableAllListeners
}