Skip to content
Merged
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
34 changes: 21 additions & 13 deletions src/utils/analytics/live-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
26 changes: 22 additions & 4 deletions tests/live-presence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ async function browser(
cookie?: string
hash?: string
storage?: Map<string, string>
noBeacon?: boolean
} = {},
) {
const events: Blob[] = []
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 })
Expand Down
Loading