Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

events.js 5.7 KB

You have to be logged in to leave a comment. Sign In
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
  1. /* eslint-disable camelcase */
  2. import { v4 as uuidv4 } from 'uuid'
  3. import Cookies from 'js-cookie'
  4. import getCsrf from './get-csrf'
  5. import parseUserAgent from './user-agent'
  6. const COOKIE_NAME = '_docs-events'
  7. const startVisitTime = Date.now()
  8. let cookieValue
  9. let pageEventId
  10. let maxScrollY = 0
  11. let pauseScrolling = false
  12. let sentExit = false
  13. export function getUserEventsId () {
  14. if (cookieValue) return cookieValue
  15. cookieValue = Cookies.get(COOKIE_NAME)
  16. if (cookieValue) return cookieValue
  17. cookieValue = uuidv4()
  18. Cookies.set(COOKIE_NAME, cookieValue, {
  19. secure: true,
  20. sameSite: 'strict',
  21. expires: 365
  22. })
  23. return cookieValue
  24. }
  25. export function sendEvent ({
  26. type,
  27. version = '1.0.0',
  28. exit_render_duration,
  29. exit_first_paint,
  30. exit_dom_interactive,
  31. exit_dom_complete,
  32. exit_visit_duration,
  33. exit_scroll_length,
  34. link_url,
  35. search_query,
  36. search_context,
  37. navigate_label,
  38. survey_vote,
  39. survey_comment,
  40. survey_email,
  41. experiment_name,
  42. experiment_variation,
  43. experiment_success,
  44. clipboard_operation
  45. }) {
  46. const body = {
  47. _csrf: getCsrf(),
  48. type, // One of page, exit, link, search, navigate, survey, experiment
  49. context: {
  50. // Primitives
  51. event_id: uuidv4(),
  52. user: getUserEventsId(),
  53. version,
  54. created: new Date().toISOString(),
  55. page_event_id: pageEventId,
  56. // Content information
  57. path: location.pathname,
  58. hostname: location.hostname,
  59. referrer: document.referrer,
  60. search: location.search,
  61. href: location.href,
  62. site_language: location.pathname.split('/')[1],
  63. // Device information
  64. // os, os_version, browser, browser_version:
  65. ...parseUserAgent(),
  66. viewport_width: document.documentElement.clientWidth,
  67. viewport_height: document.documentElement.clientHeight,
  68. // Location information
  69. timezone: new Date().getTimezoneOffset() / -60,
  70. user_language: navigator.language
  71. },
  72. // Page event
  73. // No extra fields
  74. // Exit event
  75. exit_render_duration,
  76. exit_first_paint,
  77. exit_dom_interactive,
  78. exit_dom_complete,
  79. exit_visit_duration,
  80. exit_scroll_length,
  81. // Link event
  82. link_url,
  83. // Search event
  84. search_query,
  85. search_context,
  86. // Navigate event
  87. navigate_label,
  88. // Survey event
  89. survey_vote,
  90. survey_comment,
  91. survey_email,
  92. // Experiment event
  93. experiment_name,
  94. experiment_variation,
  95. experiment_success,
  96. // Clipboard event
  97. clipboard_operation
  98. }
  99. const blob = new Blob([JSON.stringify(body)], { type: 'application/json' })
  100. navigator.sendBeacon('/events', blob)
  101. return body
  102. }
  103. function getPerformance () {
  104. const paint = performance?.getEntriesByType('paint')?.find(
  105. ({ name }) => name === 'first-contentful-paint'
  106. )
  107. const nav = performance?.getEntriesByType('navigation')?.[0]
  108. return {
  109. firstContentfulPaint: paint ? paint.startTime / 1000 : undefined,
  110. domInteractive: nav ? nav.domInteractive / 1000 : undefined,
  111. domComplete: nav ? nav.domComplete / 1000 : undefined,
  112. render: nav ? (nav.responseEnd - nav.requestStart) / 1000 : undefined
  113. }
  114. }
  115. function trackScroll () {
  116. // Throttle the calculations to no more than five per second
  117. if (pauseScrolling) return
  118. pauseScrolling = true
  119. setTimeout(() => { pauseScrolling = false }, 200)
  120. // Update maximum scroll position reached
  121. const scrollPosition = (
  122. (window.scrollY + window.innerHeight) /
  123. document.documentElement.scrollHeight
  124. )
  125. if (scrollPosition > maxScrollY) maxScrollY = scrollPosition
  126. }
  127. function sendExit () {
  128. if (sentExit) return
  129. if (document.visibilityState !== 'hidden') return
  130. sentExit = true
  131. const {
  132. render,
  133. firstContentfulPaint,
  134. domInteractive,
  135. domComplete
  136. } = getPerformance()
  137. return sendEvent({
  138. type: 'exit',
  139. exit_render_duration: render,
  140. exit_first_paint: firstContentfulPaint,
  141. exit_dom_interactive: domInteractive,
  142. exit_dom_complete: domComplete,
  143. exit_visit_duration: (Date.now() - startVisitTime) / 1000,
  144. exit_scroll_length: maxScrollY
  145. })
  146. }
  147. function initPageEvent () {
  148. const pageEvent = sendEvent({ type: 'page' })
  149. pageEventId = pageEvent?.context?.event_id
  150. }
  151. function initClipboardEvent () {
  152. ['copy', 'cut', 'paste'].forEach(verb => {
  153. document.documentElement.addEventListener(verb, () => {
  154. sendEvent({ type: 'clipboard', clipboard_operation: verb })
  155. })
  156. })
  157. }
  158. function initLinkEvent () {
  159. document.documentElement.addEventListener('click', evt => {
  160. const link = evt.target.closest('a[href^="http"]')
  161. if (!link) return
  162. sendEvent({
  163. type: 'link',
  164. link_url: link.href
  165. })
  166. })
  167. }
  168. function initExitEvent () {
  169. window.addEventListener('scroll', trackScroll)
  170. document.addEventListener('visibilitychange', sendExit)
  171. }
  172. function initNavigateEvent () {
  173. if (!document.querySelector('.sidebar-products')) return
  174. Array.from(
  175. document.querySelectorAll('.sidebar-products details')
  176. ).forEach(details => details.addEventListener(
  177. 'toggle',
  178. evt => sendEvent({
  179. type: 'navigate',
  180. navigate_label: `details ${evt.target.open ? 'open' : 'close'}: ${evt.target.querySelector('summary').innerText}`
  181. })
  182. ))
  183. document.querySelector('.sidebar-products').addEventListener('click', evt => {
  184. const link = evt.target.closest('a')
  185. if (!link) return
  186. sendEvent({
  187. type: 'navigate',
  188. navigate_label: `link: ${link.href}`
  189. })
  190. })
  191. }
  192. export default function initializeEvents () {
  193. initPageEvent() // must come first
  194. initExitEvent()
  195. initLinkEvent()
  196. initClipboardEvent()
  197. initNavigateEvent()
  198. // print event in ./print.js
  199. // survey event in ./helpfulness.js
  200. // experiment event in ./experiment.js
  201. // search event in ./search.js
  202. // redirect event in middleware/record-redirect.js
  203. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...