diff --git a/src/utils/analytics/live-browser.ts b/src/utils/analytics/live-browser.ts index 33421c5c8..a9544cab7 100644 --- a/src/utils/analytics/live-browser.ts +++ b/src/utils/analytics/live-browser.ts @@ -144,20 +144,28 @@ export function startLivePresence() { | undefined const sendLeave = () => { if (!lastPayload || !wasOnPublicPage) return - navigator.sendBeacon( - '/_a/live', - new Blob( - [ - JSON.stringify({ - ...lastPayload, - sequence: ++sequence, - kind: 'leave', - }), - ], - { type: 'application/json' }, - ), - ) + const body = JSON.stringify({ + ...lastPayload, + sequence: ++sequence, + kind: 'leave', + }) wasOnPublicPage = false + // Some clients (e.g. Apple Mail webviews, Firefox with beacons disabled) + // have no Beacon API, so fall back to a keepalive fetch. + if (typeof navigator.sendBeacon === 'function') { + navigator.sendBeacon( + '/_a/live', + new Blob([body], { type: 'application/json' }), + ) + return + } + void fetch('/_a/live', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body, + keepalive: true, + cache: 'no-store', + }).catch(() => {}) } report = (action) => send('update', action) const onVisibility = () => send('update') diff --git a/tests/live-presence.test.ts b/tests/live-presence.test.ts index 2af63aa4a..d855526f7 100644 --- a/tests/live-presence.test.ts +++ b/tests/live-presence.test.ts @@ -39,6 +39,7 @@ async function browser( cookie?: string hash?: string storage?: Map + noBeacon?: boolean } = {}, ) { const events: Blob[] = [] @@ -96,10 +97,14 @@ async function browser( navigator: { doNotTrack: options.dnt, globalPrivacyControl: options.gpc, - sendBeacon(_url: string, body: Blob) { - events.push(body) - return true - }, + ...(options.noBeacon + ? {} + : { + sendBeacon(_url: string, body: Blob) { + events.push(body) + return true + }, + }), }, window: { addEventListener(name: string, handler: () => void) { @@ -221,6 +226,19 @@ test('private navigation leaves the last public page and stops updates', async ( visitor.stop() }) +test('leaving falls back to fetch when sendBeacon is unavailable', async () => { + const visitor = await browser({ noBeacon: true }) + assert.doesNotThrow(() => visitor.handlers.get('pagehide')?.()) + visitor.handlers.get('pagehide')?.() + const messages = await visitor.messages() + assert.deepEqual( + messages.map((event) => event.kind), + ['update', 'leave'], + ) + assert.equal(messages[1].sequence, 2) + visitor.stop() +}) + test('tabs share a session but have independent presence', async () => { const first = await browser() const second = await browser({ cookie: first.document.cookie })