Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/silver-lemons-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'posthog-js': patch
---

Fix delayed event flushing after `opt_in_capturing()` (fixes cookieless mode needing reload before events are captured)
27 changes: 27 additions & 0 deletions packages/browser/src/__tests__/cookieless.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,5 +310,32 @@ describe('cookieless', () => {
expect(beforeSendMock.mock.calls[3][0].properties.$cookieless_mode).toEqual(true)
expect(posthog.sessionRecording).toBeFalsy()
})

it('should restart autocapture after opt_in_capturing in cookieless mode', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused about whether the bug is related to autocapture not being restarted on opt-in (which is what this is testing), or whether it's related to the request queue not starting (which is the title of this PR).

Is there a link to a ticket somewhere?

const { posthog } = await setup({
cookieless_mode: 'on_reject',
})

// Mock the autocapture startIfEnabled method
const mockStartIfEnabled = jest.fn()
const originalStartIfEnabled = posthog.autocapture?.startIfEnabled
if (posthog.autocapture) {
posthog.autocapture.startIfEnabled = mockStartIfEnabled
}

// Clear any previous startIfEnabled calls
mockStartIfEnabled.mockClear()

// Opt in
posthog.opt_in_capturing()

// Autocapture should be restarted immediately after opt-in
expect(mockStartIfEnabled).toHaveBeenCalledTimes(1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm I don't think this is the right test

This is just testing an implementation detail.

Ideally we would test whether an autocapture event is sent when a simulated click happens


// Restore original method
if (posthog.autocapture && originalStartIfEnabled) {
posthog.autocapture.startIfEnabled = originalStartIfEnabled
}
})
})
})
3 changes: 3 additions & 0 deletions packages/browser/src/posthog-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2925,6 +2925,9 @@ export class PostHog {
this.surveys.loadIfEnabled()
}

// Restart autocapture after opting in
this.autocapture?.startIfEnabled()

// Don't capture if captureEventName is null or false
if (isUndefined(options?.captureEventName) || options?.captureEventName) {
this.capture(options?.captureEventName ?? '$opt_in', options?.captureProperties, { send_instantly: true })
Expand Down
Loading