Skip to content

Commit 478f586

Browse files
authored
fix: init rrweb with load event or with document.readyState (#1089)
1 parent 7b2c2ae commit 478f586

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

packages/session-recorder/src/index.ts

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ const MAX_CHUNK_SIZE = 950 * 1024 // ~950KB
9494
const encoder = new TextEncoder()
9595
const decoder = new TextDecoder()
9696

97-
let inited: (() => void) | false | undefined = false
97+
let initCleanUp: (() => void) | false | undefined = false
9898
let tracer: Tracer
9999
let lastKnownSession: string
100100
let sessionStartTime = 0
@@ -104,17 +104,18 @@ let logCounter = 1
104104

105105
const SplunkRumRecorder = {
106106
get inited(): boolean {
107-
return Boolean(inited)
107+
return Boolean(initCleanUp)
108108
},
109109

110110
init(config: SplunkRumRecorderConfig): void {
111-
if (inited) {
111+
if (initCleanUp) {
112112
return
113113
}
114114

115-
if (typeof window === 'undefined') {
116-
console.error("SplunkSessionRecorder can't be run in non-browser environments.")
117-
return
115+
if (typeof window !== 'object') {
116+
throw Error(
117+
'SplunkSessionRecorder Error: This library is intended to run in a browser environment. Please ensure the code is evaluated within a browser context.',
118+
)
118119
}
119120

120121
let tracerProvider: BasicTracerProvider | ProxyTracerProvider = trace.getTracerProvider() as BasicTracerProvider
@@ -213,7 +214,7 @@ const SplunkRumRecorder = {
213214
lastKnownSession = SplunkRum.getSessionId()
214215
sessionStartTime = Date.now()
215216

216-
inited = record({
217+
const initParams = {
217218
maskAllInputs: true,
218219
maskTextSelector: '*',
219220
...rrwebConf,
@@ -284,10 +285,21 @@ const SplunkRumRecorder = {
284285
processor.onLog(log)
285286
}
286287
},
287-
})
288+
}
289+
290+
const initFn = () => {
291+
initCleanUp = record(initParams)
292+
}
293+
294+
if (document.readyState === 'complete' || document.readyState === 'interactive') {
295+
initFn()
296+
} else {
297+
window.addEventListener('load', initFn, { once: true })
298+
initCleanUp = () => window.removeEventListener('load', initFn)
299+
}
288300
},
289301
resume(): void {
290-
if (!inited) {
302+
if (!initCleanUp) {
291303
return
292304
}
293305

@@ -299,7 +311,7 @@ const SplunkRumRecorder = {
299311
}
300312
},
301313
stop(): void {
302-
if (!inited) {
314+
if (!initCleanUp) {
303315
return
304316
}
305317

@@ -310,12 +322,12 @@ const SplunkRumRecorder = {
310322
paused = true
311323
},
312324
deinit(): void {
313-
if (!inited) {
325+
if (!initCleanUp) {
314326
return
315327
}
316328

317-
inited()
318-
inited = false
329+
initCleanUp()
330+
initCleanUp = false
319331
},
320332
}
321333

0 commit comments

Comments
 (0)