Skip to content

Commit

Permalink
fix: only wrap once when patching (#1245)
Browse files Browse the repository at this point in the history
* fix: only wrap once when patching

* only init once

* fix

* we might actually want to wrap twice e.g. trace headers
  • Loading branch information
pauldambra committed Jun 14, 2024
1 parent b4b0050 commit 554f061
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/__tests__/extensions/replay/rrweb-plugins/patch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { patch } from '../../../../extensions/replay/rrweb-plugins/patch'

const fakeWindow = {
fakeFetch: () => {},
}

// JS-DOM doesn't have fetch and its fake XHR doesn't work with our patch,
// so we can't test them directly
describe('patch', () => {
it('marks a function as wrapped', () => {
patch(fakeWindow, 'fakeFetch', () => () => {})
// eslint-disable-next-line compat/compat
expect((fakeWindow.fakeFetch as any).__posthog_wrapped__).toBe(true)
})
})
12 changes: 11 additions & 1 deletion src/loader-recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ function initFetchObserver(
}
}

let initialisedHandler: listenerHandler | null = null
function initNetworkObserver(
callback: networkCallback,
win: IWindow, // top window or in an iframe
Expand All @@ -493,6 +494,14 @@ function initNetworkObserver(
//
}
}

if (initialisedHandler) {
logger.warn('Network observer already initialised, doing nothing')
return () => {
// the first caller should already have this handler and will be responsible for teardown
}
}

const networkOptions = (
options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions
) as Required<NetworkRecordOptions>
Expand Down Expand Up @@ -520,11 +529,12 @@ function initNetworkObserver(
fetchObserver = initFetchObserver(cb, win, networkOptions)
}

return () => {
initialisedHandler = () => {
performanceObserver()
xhrObserver()
fetchObserver()
}
return initialisedHandler
}

// use the plugin name so that when this functionality is adopted into rrweb
Expand Down

0 comments on commit 554f061

Please sign in to comment.