-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathurlContexts.ts
77 lines (67 loc) · 2.22 KB
/
urlContexts.ts
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
import type { RelativeTime, Observable } from '@datadog/browser-core'
import { SESSION_TIME_OUT_DELAY, relativeNow, ContextHistory } from '@datadog/browser-core'
import type { UrlContext } from '../rawRumEvent.types'
import type { LocationChange } from '../browser/locationChangeObservable'
import type { LifeCycle } from './lifeCycle'
import { LifeCycleEventType } from './lifeCycle'
/**
* We want to attach to an event:
* - the url corresponding to its start
* - the referrer corresponding to the previous view url (or document referrer for initial view)
*/
export const URL_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY
export interface UrlContexts {
findUrl: (startTime?: RelativeTime) => UrlContext | undefined
stop: () => void
}
export function startUrlContexts(
lifeCycle: LifeCycle,
locationChangeObservable: Observable<LocationChange>,
location: Location
) {
const urlContextHistory = new ContextHistory<UrlContext>(URL_CONTEXT_TIME_OUT_DELAY)
let previousViewUrl: string | undefined
lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, ({ endClocks }) => {
urlContextHistory.closeActive(endClocks.relative)
})
lifeCycle.subscribe(LifeCycleEventType.VIEW_CREATED, ({ startClocks }) => {
const viewUrl = location.href
urlContextHistory.add(
buildUrlContext({
url: viewUrl,
referrer: !previousViewUrl ? document.referrer : previousViewUrl,
}),
startClocks.relative
)
previousViewUrl = viewUrl
})
const locationChangeSubscription = locationChangeObservable.subscribe(({ newLocation }) => {
const current = urlContextHistory.find()
if (current) {
const changeTime = relativeNow()
urlContextHistory.closeActive(changeTime)
urlContextHistory.add(
buildUrlContext({
url: newLocation.href,
referrer: current.view.referrer,
}),
changeTime
)
}
})
function buildUrlContext({ url, referrer }: { url: string; referrer: string }) {
return {
view: {
url,
referrer,
},
}
}
return {
findUrl: (startTime?: RelativeTime) => urlContextHistory.find(startTime),
stop: () => {
locationChangeSubscription.unsubscribe()
urlContextHistory.stop()
},
}
}