:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): load a new player frame element on each retry (#119322)
posthog[bot]79157549d8b5
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsxindex 98fbe2c791cf..15a376395568 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx@@ -8,6 +8,7 @@ import { SessionPlayerState } from '~/types'import { setupSessionRecordingTest } from './__mocks__/test-setup'import { PlayerFrame } from './PlayerFrame'+import { PlayerFrameOverlay } from './PlayerFrameOverlay'import { sessionRecordingPlayerLogic } from './sessionRecordingPlayerLogic'describe('PlayerFrame', () => {@@ -17,6 +18,17 @@ describe('PlayerFrame', () => {setupSessionRecordingTest()})+ // Each retry renders a new frame element, so a test looks the frame up again after each one.+ function currentFrame(container: HTMLElement): HTMLIFrameElement {+ const iframe = container.querySelector('iframe.PlayerFrame__document')+ if (!(iframe instanceof HTMLIFrameElement)) {+ throw new Error('the player did not render its frame')+ }+ // jsdom leaves the frame document mid-load, and the player judges a document that finished loading.+ Object.defineProperty(iframe.contentDocument!, 'readyState', { value: 'complete', configurable: true })+ return iframe+ }+function renderPlayerFrame(): HTMLIFrameElement {const { container } = render(<Provider>@@ -25,13 +37,7 @@ describe('PlayerFrame', () => {</BindLogic></Provider>)- const iframe = container.querySelector('iframe.PlayerFrame__document')- if (!(iframe instanceof HTMLIFrameElement)) {- throw new Error('the player did not render its frame')- }- // jsdom leaves the frame document mid-load, and the player judges a document that finished loading.- Object.defineProperty(iframe.contentDocument!, 'readyState', { value: 'complete', configurable: true })- return iframe+ return currentFrame(container)}it('mounts the player on the frame document once the frame loads', () => {@@ -66,19 +72,19 @@ describe('PlayerFrame', () => {act(() => {jest.advanceTimersByTime(10000)})- expect(container.querySelector('iframe')).toBe(iframe)expect(captureSpy).toHaveBeenCalledWith('replay player frame load retried',- expect.objectContaining({ attempt: 1 })+ expect.objectContaining({ attempt: 1, restarts: 0 }))- // The retry changes the src, and the reloaded frame's load also never fires. The frame- // gets MAX_PLAYER_FRAME_LOAD_RETRIES retries, so failures 1 and 2 retry and failure 3- // reaches the error state.+ // The retry replaces the frame, because a frame stuck on about:blank can ignore a new src.+ // The new frame's load also never fires. The frame gets MAX_PLAYER_FRAME_LOAD_RETRIES+ // retries, so failures 1 and 2 retry and failure 3 reaches the error state.act(() => {jest.advanceTimersByTime(1000)})- expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')+ expect(currentFrame(container)).not.toBe(iframe)+ expect(currentFrame(container)).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')act(() => {jest.advanceTimersByTime(10000)@@ -91,7 +97,7 @@ describe('PlayerFrame', () => {act(() => {jest.advanceTimersByTime(2000)})- expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=2')+ expect(currentFrame(container)).toHaveAttribute('src', '/replay_player_frame/index.html?retry=2')act(() => {jest.advanceTimersByTime(10000)@@ -140,8 +146,7 @@ describe('PlayerFrame', () => {act(() => {jest.advanceTimersByTime(1000)})- expect(container.querySelector('iframe')).toBe(iframe)- expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')+ expect(currentFrame(container)).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')} finally {jest.useRealTimers()}@@ -174,25 +179,28 @@ describe('PlayerFrame', () => {try {const captureSpy = jest.spyOn(posthog, 'capture')const captureExceptionSpy = jest.spyOn(posthog, 'captureException')- const iframe = renderPlayerFrame()+ const container = renderPlayerFrame().parentElement!const logic = sessionRecordingPlayerLogic(logicProps)- fireEvent.load(iframe)+ fireEvent.load(currentFrame(container))act(() => {jest.advanceTimersByTime(1000)})- expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')+ const retriedFrame = currentFrame(container)+ expect(retriedFrame).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')// A browser error page is cross-origin to the app, so the frame's document is unreadable.- Object.defineProperty(iframe, 'contentDocument', { value: null, configurable: true })- fireEvent.load(iframe)+ Object.defineProperty(retriedFrame, 'contentDocument', { value: null, configurable: true })+ fireEvent.load(retriedFrame)act(() => {jest.advanceTimersByTime(2000)})- expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=2')+ expect(currentFrame(container)).toHaveAttribute('src', '/replay_player_frame/index.html?retry=2')expect(logic.values.currentPlayerState).not.toBe(SessionPlayerState.ERROR)- fireEvent.load(iframe)+ const lastFrame = currentFrame(container)+ Object.defineProperty(lastFrame, 'contentDocument', { value: null, configurable: true })+ fireEvent.load(lastFrame)expect(logic.values.currentPlayerState).toBe(SessionPlayerState.ERROR)expect(@@ -210,6 +218,68 @@ describe('PlayerFrame', () => {}})+ // A retry from the error card must load a new frame. A page reload repeats the same failed load.+ it('loads a new frame and mounts the player when the viewer retries from the error state', () => {+ const onLine = jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false)+ try {+ const captureSpy = jest.spyOn(posthog, 'capture')+ const { container } = render(+ <Provider>+ <BindLogic logic={sessionRecordingPlayerLogic} props={logicProps}>+ <PlayerFrame />+ <PlayerFrameOverlay />+ </BindLogic>+ </Provider>+ )+ const logic = sessionRecordingPlayerLogic(logicProps)+ const failedFrame = currentFrame(container)+ fireEvent.load(failedFrame)+ expect(logic.values.currentPlayerState).toBe(SessionPlayerState.ERROR)+ onLine.mockReturnValue(true)++ fireEvent.click(container.querySelector('[data-attr="replay-overlay-retry-player-frame"]')!)++ expect(captureSpy).toHaveBeenCalledWith(+ 'replay player frame load restarted',+ expect.objectContaining({ restarts: 1, browserOnline: true })+ )+ expect(logic.values.currentPlayerState).not.toBe(SessionPlayerState.ERROR)+ expect(currentFrame(container)).not.toBe(failedFrame)+ const frameDocument = currentFrame(container).contentDocument!+ frameDocument.open()+ frameDocument.write('<div id="player-frame-content"></div>')+ frameDocument.close()+ fireEvent.load(currentFrame(container))+ expect(logic.values.rootFrame).toBe(frameDocument.getElementById('player-frame-content'))+ } finally {+ onLine.mockRestore()+ }+ })++ // The failure count starts again after a restart, so only the restart count tells these reports apart+ // from the first round of automatic retries.+ it('reports the restart count with a frame failure after the viewer retries', () => {+ const onLine = jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false)+ try {+ const captureSpy = jest.spyOn(posthog, 'capture')+ const container = renderPlayerFrame().parentElement!+ const logic = sessionRecordingPlayerLogic(logicProps)+ fireEvent.load(currentFrame(container))+ expect(logic.values.currentPlayerState).toBe(SessionPlayerState.ERROR)+ onLine.mockReturnValue(true)++ act(() => logic.actions.restartPlayerFrameLoad())+ fireEvent.load(currentFrame(container))++ expect(captureSpy).toHaveBeenCalledWith(+ 'replay player frame load retried',+ expect.objectContaining({ attempt: 1, restarts: 1 })+ )+ } finally {+ onLine.mockRestore()+ }+ })+// A frame cannot load while the browser is offline, so the player shows its error at once instead of// staying blank while it waits for a connection that may not come back.it('shows the player error without a retry while the browser is offline', () => {diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsxindex e19b2c32d4b8..0d1964b9b800 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx@@ -27,7 +27,7 @@ export const PlayerFrame = (): JSX.Element => {useValues(sessionRecordingPlayerLogic)const { setScale, setRootFrame, playerFrameDocumentLoadFailed } = useActions(sessionRecordingPlayerLogic)- // A frame loads again only when its src changes, so each retry adds a query string the server ignores.+ // Each retry adds a query string the server ignores, so the browser fetches the shell again.const frameSrc = playerFrameLoadRetries ? `${PLAYER_FRAME_SRC}?retry=${playerFrameLoadRetries}` : PLAYER_FRAME_SRCconst iframeRef = useRef<HTMLIFrameElement | null>(null)@@ -150,6 +150,9 @@ export const PlayerFrame = (): JSX.Element => {return (<div ref={containerRef} className={clsx('PlayerFrame ph-no-capture', isIOS() && 'PlayerFrame--ios')}><iframe+ // A frame can stay on about:blank with its navigation never committed, and a new src on that+ // element does not always start a new navigation. A new element does.+ key={frameSrc}ref={iframeRef}className="PlayerFrame__document"src={frameSrc}diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsxindex 590cf47eb00e..a265d4f41b95 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx@@ -91,7 +91,7 @@ const PlayerFrameOverlayContent = (): JSX.Element | null => {sessionPlayerMetaData,matchingEventSkipTarget,} = useValues(sessionRecordingPlayerLogic)- const { setPlay, retryLoadingSnapshots } = useActions(sessionRecordingPlayerLogic)+ const { setPlay, retryLoadingSnapshots, restartPlayerFrameLoad } = useActions(sessionRecordingPlayerLogic)const handlePlay = (e: MouseEvent): void => {e.stopPropagation()@@ -149,7 +149,7 @@ const PlayerFrameOverlayContent = (): JSX.Element | null => {</div><div className="text-secondary text-sm text-center">{playerFrameDocumentFailed- ? "Your browser couldn't load the player. Check your internet connection and reload the page. If it keeps happening, a browser extension or security setting may be blocking it. Try turning off extensions for PostHog or using another browser."+ ? "Your browser couldn't load the player. Check your internet connection and retry. If it keeps happening, a browser extension or security setting may be blocking it. Try turning off extensions for PostHog or using another browser.": isMissingFullSnapshot? 'This part of the recording is missing the snapshot data needed to render it. The data never reached PostHog, usually because the browser was closed or went offline before the recording finished uploading.': isUnauthorized@@ -177,7 +177,21 @@ const PlayerFrameOverlayContent = (): JSX.Element | null => {Retry</LemonButton>)}- {!isMissingFullSnapshot && !isUnauthorized && !isRecoverable && (+ {playerFrameDocumentFailed && (+ <LemonButton+ data-attr="replay-overlay-retry-player-frame"+ onClick={(e) => {+ e.stopPropagation()+ restartPlayerFrameLoad()+ }}+ type="primary"+ fullWidth+ center+ >+ Retry+ </LemonButton>+ )}+ {!playerFrameDocumentFailed && !isMissingFullSnapshot && !isUnauthorized && !isRecoverable && (<LemonButtondata-attr="replay-overlay-reload"onClick={() => {diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 725195c8898e..de891c84f6f1 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -843,6 +843,7 @@ export interface sessionRecordingPlayerLogicValues {playerError: string | nullplayerFrameDocumentFailed: booleanplayerFrameLoadFailures: number+ playerFrameLoadRestarts: numberplayerFrameLoadRetries: numberplayerFrameLoadStopped: booleanplayerSpeed: number@@ -1137,6 +1138,9 @@ export interface sessionRecordingPlayerLogicActions {restartIframePlayback: () => {value: true}+ restartPlayerFrameLoad: () => {+ value: true+ }retryLoadingSnapshots: () => {value: true}@@ -1637,6 +1641,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(playerFrameDocumentLoadFailed: (iframe: HTMLIFrameElement | null) => ({ iframe }),retryPlayerFrameLoad: true,stopRetryingPlayerFrameLoad: true,+ restartPlayerFrameLoad: true,fingerprintReported: (fingerprint: string) => ({ fingerprint }),setDebugSnapshotTypes: (types: EventType[]) => ({ types }),setDebugSnapshotIncrementalSources: (incrementalSources: IncrementalSource[]) => ({ incrementalSources }),@@ -1842,10 +1847,22 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(},],isBuffering: [true, { startBuffer: () => true, endBuffer: () => false }],- playerFrameLoadFailures: [0, { playerFrameDocumentLoadFailed: (failures) => failures + 1 }],- // PlayerFrame adds this to the frame's src, because a frame loads again only when its src changes.- playerFrameLoadRetries: [0, { retryPlayerFrameLoad: (retries) => retries + 1 }],- playerFrameLoadStopped: [false, { stopRetryingPlayerFrameLoad: () => true }],+ // A restart from the error state gives the frame its full set of retries again.+ playerFrameLoadFailures: [+ 0,+ { playerFrameDocumentLoadFailed: (failures) => failures + 1, restartPlayerFrameLoad: () => 0 },+ ],+ // The failure count starts again on a restart, so the reports carry this to tell a viewer's retry apart.+ playerFrameLoadRestarts: [0, { restartPlayerFrameLoad: (restarts) => restarts + 1 }],+ // PlayerFrame keys the frame on this and adds it to the frame's src, so each retry loads a new frame element.+ playerFrameLoadRetries: [+ 0,+ { retryPlayerFrameLoad: (retries) => retries + 1, restartPlayerFrameLoad: (retries) => retries + 1 },+ ],+ playerFrameLoadStopped: [+ false,+ { stopRetryingPlayerFrameLoad: () => true, restartPlayerFrameLoad: () => false },+ ],playerError: [null as string | null,{@@ -2671,6 +2688,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(const report = {sessionRecordingId: props.sessionRecordingId,attempt: values.playerFrameLoadFailures,+ restarts: values.playerFrameLoadRestarts,...getPlayerFrameLoadDiagnostics(iframe),}// A load retried while offline fails again, and a connection can stay away for the rest of the@@ -2697,6 +2715,13 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>({ pauseOnPageHidden: false })},+ restartPlayerFrameLoad: () => {+ posthog.capture('replay player frame load restarted', {+ sessionRecordingId: props.sessionRecordingId,+ restarts: values.playerFrameLoadRestarts,+ browserOnline: navigator.onLine,+ })+ },playerErrorSeen: ({ error }) => {const fingerprint = encodeURIComponent(error.message + error.filename + error.lineno + error.colno)if (values.reportedReplayerErrors.has(fingerprint)) {