fix: replace AbortController with Promise.race to avoid SW hanging fetch bug

Root cause: AbortController signals don't properly propagate through
Service Worker fetch handlers (known Chrome/Safari bug), causing the
fetch to hang indefinitely on mobile browsers instead of timing out.

Fix: replace AbortController-based timeout in api() with Promise.race
against a simple setTimeout. Also:
- Stop all MediaStream tracks explicitly in stopScanning()
- Add 200ms yield point before API call for hardware release
- Bypass SW for API requests entirely (no caching needed for lookups)
- Bump SW cache to v11
- Add outer try/catch safety net in handleBarcode
This commit is contained in:
2026-06-02 18:43:17 -04:00
parent dd63dc97d5
commit 52f801675e
2 changed files with 78 additions and 57 deletions
+6 -18
View File
@@ -3,7 +3,7 @@
// Caches app shell + CDN deps. Network-first for API, cache fallback for static.
// ═══════════════════════════════════════════════════════════════════════════
const CACHE_NAME = 'canteen-v10';
const CACHE_NAME = 'canteen-v11';
// App shell — core resources needed to boot the PWA
const APP_SHELL = [
@@ -73,24 +73,12 @@ self.addEventListener('fetch', (event) => {
return;
}
// API GET calls: network-first, cache fallback (offline reads)
// API POST/PUT/DELETE: pass through — main thread handles offline queuing
// API requests: pass through — don't intercept at all.
// The SW cache doesn't help with real-time lookups, and SW interception
// combined with main-thread timeouts can cause indefinite hangs on mobile
// (AbortController signal doesn't propagate through SW fetch handler).
if (url.pathname.startsWith('/api/')) {
if (event.request.method === 'GET') {
event.respondWith(
fetch(event.request)
.then((response) => {
if (response.ok) {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
}
return response;
})
.catch(() => caches.match(event.request))
);
}
// Non-GET API calls: pass through — main thread queues offline writes
return;
return; // Don't call event.respondWith — let the request go direct
}
// Static assets (local + CDN): network-first, cache fallback