: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(heatmaps): unstick heatmap on a recording background (#88678)
posthog[bot]463561c5a921
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e1114efdf549..fdbc225e5820 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6609,9 +6609,9 @@ snapshots:scenes-app-heatmap-new--unauthorized-iframe--light:hash: v1.k794b7964.8e355023754bf9c2c1dc31cbadba79e6b524ad9a66528c649ab150f7eaf0cc05.yqUC0NlgolBVjXQsucJcRfdlu5npQvynKZSy7oAnd_8scenes-app-heatmap-recording--recording-mode-with-clickmap--dark:- hash: v1.k794b7964.3499aad6c2502ef406a4482b07fc63e130419f017d378e67f368d037bcfe60cd.bq5I6_BkW5qM66IZeNnjtJhQ6b2_3ch-I0qGo_yKKT0+ hash: v1.k794b7964.6c923e6ba9f58ab555cc4dc2b9c1789d8a72f549765ddde70c1f3a7b73cdfbe6.QQa2mS_nUNyAH6iXIu6RYQ5wu9YFzB6GjsocU8M4PmQscenes-app-heatmap-recording--recording-mode-with-clickmap--light:- hash: v1.k794b7964.22f3a94ca40cb149e4304284f5a3ed613728ed22a1d4554fa94754aca6dc38e8.RL9cCxn6_8zy2HgMxnfhUCDvQk_-tWwn_vmZNIZjF4I+ hash: v1.k794b7964.09522d7c70db3016e974a1cc8def11a5c9594e2f0f4df50fa4cf290d54129c07.kwWeHESZph4vfH_U-uOGsccGiePlAsCnCzuQvd9ptnMscenes-app-heatmaps-saved--list--dark:hash: v1.k794b7964.8368377e136c567c3c500c97924486837234c230858baf0eb14678b6900d68c6.qpjMZIE3Ii8vpyLrfaKjCdym7waJtp38DGez1iugMMoscenes-app-heatmaps-saved--list--light:diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.tsindex 5667038fe251..1aa92810a040 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts@@ -18,6 +18,7 @@ import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { ExporterFormat, RecordingSegment, RecordingSnapshot } from '~/types'import { analysisNudgeLogic } from 'products/replay_vision/frontend/logics/analysisNudgeLogic'+import { isUsableHeatmapUrl } from 'products/web_analytics/frontend/heatmaps/replayIframeData'import { deletedRecordingsLogic } from '../deletedRecordingsLogic'import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLogic'@@ -93,6 +94,19 @@ describe('findNewEvents', () => {})})+describe('isUsableHeatmapUrl', () => {+ it.each([+ [undefined, false],+ ['', false],+ [' ', false],+ // mobile snapshots with no captured href resolve to the literal 'unknown'+ ['unknown', false],+ ['https://example.com/pricing', true],+ ] as const)('isUsableHeatmapUrl(%s) → %s', (input, expected) => {+ expect(isUsableHeatmapUrl(input)).toBe(expected)+ })+})+describe('stripRrwebScriptShims', () => {const countTag = (html: string, tag: string): number => (html.match(new RegExp(`<${tag}\\b`, 'gi')) || []).lengthdiff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex f35bfba652cf..8624b7e26142 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -59,6 +59,7 @@ import { analysisNudgeLogic } from 'products/replay_vision/frontend/logics/analyimport {MAX_REPLAY_IFRAME_HTML_CHARS,ReplayIframeData,+ isUsableHeatmapUrl,persistReplayIframeData,} from 'products/web_analytics/frontend/heatmaps/replayIframeData'@@ -239,6 +240,8 @@ export function stripRrwebScriptShims(html: string): string {}const SNAPSHOT_REJECTION_PROBLEM = {+ not_ready: 'This recording has not finished loading this frame yet.',+ no_url: 'This moment has no page address to build a heatmap for.',too_large: 'This part of the recording is too large to use as a heatmap background.',storage_failed: "Couldn't save this moment as a heatmap background.",} as const@@ -3126,6 +3129,13 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(const rawIframeHtml = iframe?.contentWindow?.document?.documentElement?.innerHTMLconst resolution = values.resolutionif (!rawIframeHtml || !resolution) {+ rejectHeatmapSnapshot('not_ready', rawIframeHtml?.length ?? 0)+ return+ }++ const url = values.currentURL?.trim()+ if (!isUsableHeatmapUrl(url)) {+ rejectHeatmapSnapshot('no_url', rawIframeHtml.length)return}@@ -3141,7 +3151,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(width: resolution.width,height: resolution.height,startDateTime: values.sessionPlayerMetaData?.start_time,- url: values.currentURL,+ url,}const key = persistReplayIframeData(data)if (!key) {diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.tsindex f3fb5d828bd5..07e58d157823 100644--- a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts+++ b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.test.ts@@ -2,6 +2,7 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'import { initKeaTests } from '~/test/init'@@ -101,6 +102,84 @@ describe('heatmapsBrowserLogic', () => {})})+ describe('recording background href', () => {+ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)+ jest.spyOn(global, 'fetch').mockResolvedValue({+ status: 200,+ json: async () => ({ results: [] }),+ } as any)+ router.actions.push('/heatmaps/recording')+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ // The recording path has no dataUrl; the href comes from the snapshot. onIframeLoad used to+ // overwrite it with an empty string, so the query never ran and the heatmap loaded forever.+ it('keeps the snapshot href when the iframe loads without a dataUrl', async () => {+ const logic = heatmapsBrowserLogic({ iframeRef: { current: null } })+ logic.mount()+ const dataLogic = heatmapDataLogic({ context: 'in-app' })++ logic.actions.setReplayIframeData({+ html: '<html></html>',+ width: 100,+ height: 100,+ startDateTime: undefined,+ url: 'https://example.com/pricing',+ })+ await expectLogic(logic).toFinishAllListeners()+ expect(dataLogic.values.href).toBe('https://example.com/pricing')++ logic.actions.onIframeLoad()+ await expectLogic(logic).toFinishAllListeners()+ expect(dataLogic.values.href).toBe('https://example.com/pricing')+ })+ })++ describe('non-recording stale href', () => {+ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)+ jest.spyOn(global, 'fetch').mockResolvedValue({+ status: 200,+ json: async () => ({ results: [] }),+ } as any)+ router.actions.push('/heatmaps/abc123')+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ // Open a heatmap with a page URL, then open one without a data URL (e.g. a saved heatmap+ // with no custom data URL). Without clearing, onIframeLoad would re-query the previous+ // page's href and repaint its click data over the page now in the frame.+ it('clears the previous href when the iframe loads without a dataUrl', async () => {+ const logic = heatmapsBrowserLogic({ iframeRef: { current: null } })+ logic.mount()+ const dataLogic = heatmapDataLogic({ context: 'in-app' })++ logic.actions.setDisplayUrl('https://example.com/a')+ await expectLogic(logic).toFinishAllListeners()+ expect(dataLogic.values.href).toBe('https://example.com/a')++ logic.actions.setDataUrlUserTouched(true)+ logic.actions.setDisplayUrl('https://example.com/b')+ logic.actions.setDataUrl(null)+ await expectLogic(logic).toFinishAllListeners()+ // setDataUrl(null) leaves href alone, so it still points at the previous page here.+ expect(dataLogic.values.href).toBe('https://example.com/a')++ logic.actions.onIframeLoad()+ await expectLogic(logic).toFinishAllListeners()+ expect(dataLogic.values.href).toBe('')+ })+ })+describe('iframeBanner', () => {beforeEach(() => {initKeaTests()diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.tsindex 1a27d34e3380..03c17d8df60d 100644--- a/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts+++ b/products/web_analytics/frontend/heatmaps/components/heatmapsBrowserLogic.ts@@ -42,6 +42,7 @@ import type { HeatmapPreflightResponseApi } from 'products/web_analytics/frontenimport {ReplayIframeData,getStoredRecordingBackground,+ isUsableHeatmapUrl,removeReplayIframeDataFromLocalStorage,} from '../replayIframeData'@@ -499,7 +500,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([false,{setReplayIframeData: (_, { replayIframeData }) =>- !!replayIframeData?.url?.trim().length && !!replayIframeData?.html.trim().length,+ isUsableHeatmapUrl(replayIframeData?.url) && !!replayIframeData?.html.trim().length,},],replayIframeData: [@@ -662,7 +663,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([}},setReplayIframeData: ({ replayIframeData }) => {- if (replayIframeData && replayIframeData.url) {+ if (isUsableHeatmapUrl(replayIframeData?.url)) {actions.setHref(replayIframeData.url)// Auto-detect match type for replay data URLs tooconst isPattern = isUrlPattern(replayIframeData.url)@@ -698,18 +699,22 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([onIframeLoad: () => {actions.stopTrackingLoading()- // it should be impossible to load an iframe without a dataUrl- // right?!- const url = values.dataUrl ?? ''- actions.setHref(url)-- // Ensure match type is set correctly when iframe loads- const isPattern = isUrlPattern(url)- actions.setHrefMatchType(isPattern ? 'pattern' : 'exact')+ // The recording background path has no dataUrl; its href comes from the snapshot. Setting+ // href to an empty string here would blank the query and leave the heatmap loading forever.+ const url = values.dataUrl?.trim()+ if (url) {+ actions.setHref(url)+ actions.setHrefMatchType(isUrlPattern(url) ? 'pattern' : 'exact')+ } else if (!values.hasValidReplayIframeData) {+ // No page URL and no recording snapshot: clear the stale href so a previous page's+ // heatmap does not repaint over the page now in the frame.+ actions.setHref('')+ actions.setHrefMatchType('exact')+ }actions.loadHeatmap()posthog.capture('in-app heatmap iframe loaded', {- inapp_heatmap_page_url_visited: values.dataUrl,+ inapp_heatmap_page_url_visited: values.dataUrl ?? values.replayIframeData?.url,inapp_heatmap_filters: values.heatmapFilters,inapp_heatmap_color_palette: values.heatmapColorPalette,inapp_heatmap_fixed_position_mode: values.heatmapFixedPositionMode,diff --git a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.tsindex 661844d339b8..a2a15e1a0483 100644--- a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts+++ b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts@@ -352,7 +352,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([{loadElementStats: async (_, breakpoint) => {await breakpoint(150)- // heatmapDataLogic's href gets clobbered to '' by onIframeLoad in this scene,+ // heatmapDataLogic's href is shared and driven by the browser data-URL flow,// so the replay payload's URL is the stable source of truth hereconst url = values.replayIframeData?.url?.trim()if (!url) {diff --git a/products/web_analytics/frontend/heatmaps/replayIframeData.ts b/products/web_analytics/frontend/heatmaps/replayIframeData.tsindex bffcde7adda8..b1296d6e4e33 100644--- a/products/web_analytics/frontend/heatmaps/replayIframeData.ts+++ b/products/web_analytics/frontend/heatmaps/replayIframeData.ts@@ -13,6 +13,12 @@ export interface ReplayIframeData {export const ReplayIframeDatakeyPrefix = 'ph_replay_fixed_heatmap_'+// Recordings with no captured href get the synthesized 'unknown', which a heatmap query cannot use.+export function isUsableHeatmapUrl(url: string | undefined | null): url is string {+ const trimmed = url?.trim()+ return !!trimmed && trimmed !== 'unknown'+}+// Serializing the replayed DOM allocates several full copies of this on the main thread, in a tab// that is already holding a decoded recording. Past roughly this size that spike is what kills the// renderer.