forked from utags/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdom-watcher.ts
More file actions
101 lines (86 loc) · 2.13 KB
/
Copy pathdom-watcher.ts
File metadata and controls
101 lines (86 loc) · 2.13 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
type Callback = () => void
// --- URL Watcher ---
const urlCallbacks = new Set<Callback>()
let urlWatcherInstalled = false
function triggerUrlCallbacks() {
for (const cb of urlCallbacks) {
try {
cb()
} catch (error) {
console.error(error)
}
}
}
export function onUrlChange(callback: Callback): () => void {
urlCallbacks.add(callback)
if (!urlWatcherInstalled) {
installUrlWatcher()
urlWatcherInstalled = true
}
return () => {
urlCallbacks.delete(callback)
}
}
function installUrlWatcher() {
try {
const origPush = history.pushState
history.pushState = function (...args: any[]) {
const ret = origPush.apply(history, args as any)
triggerUrlCallbacks()
return ret
} as typeof history.pushState
} catch {}
try {
const origReplace = history.replaceState
history.replaceState = function (...args: any[]) {
const ret = origReplace.apply(history, args as any)
triggerUrlCallbacks()
return ret
} as typeof history.replaceState
} catch {}
globalThis.addEventListener('popstate', triggerUrlCallbacks)
globalThis.addEventListener('hashchange', triggerUrlCallbacks)
}
// --- DOM Watcher ---
const domCallbacks = new Set<Callback>()
let domObserver: MutationObserver | undefined
function triggerDomCallbacks() {
for (const cb of domCallbacks) {
try {
cb()
} catch (error) {
console.error(error)
}
}
}
export function onDomChange(callback: Callback): () => void {
domCallbacks.add(callback)
ensureDomObserver()
return () => {
domCallbacks.delete(callback)
}
}
function ensureDomObserver() {
if (domObserver) return
const root = document.body || document.documentElement
if (!root) {
// If body/documentElement is not ready, wait for it
if (document.readyState === 'loading') {
document.addEventListener(
'DOMContentLoaded',
() => {
ensureDomObserver()
},
{ once: true }
)
}
return
}
domObserver = new MutationObserver(() => {
triggerDomCallbacks()
})
domObserver.observe(root, {
childList: true,
subtree: true,
})
}