diff --git a/frontend/src/shared/serviceClient.ts b/frontend/src/shared/serviceClient.ts index 762857cb..fee2b254 100644 --- a/frontend/src/shared/serviceClient.ts +++ b/frontend/src/shared/serviceClient.ts @@ -41,13 +41,19 @@ function _flush(): void { const batch = _queue.splice(0); // Ship whole queue in one POST; /service/submit accepts a single object or array. const body = JSON.stringify(batch.length === 1 ? batch[0] : batch); + // keepalive lets the request outlive a closing window, so the last batch isn't eaten on quit. fetch(`${API_BASE}/service/submit`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, + keepalive: true, }).catch(() => {}); } +if (typeof window !== 'undefined') { + window.addEventListener('pagehide', () => _flush()); +} + export function sync(data: Record = {}, opts: { immediate?: boolean } = {}): void { _lastTs = Date.now(); // Stamp submission id + client ts so the cloud dedupes retries and orders by happen-time.