Question presented to candidate: "You want to log a 'page view ended' analytics event the moment a user closes the tab or navigates away. A normal fetch() call in a beforeunload/pagehide handler is unreliable — why, and what would you use instead?"
What a strong answer should cover:
- 📌 Interview term:
navigator.sendBeacon(url, data)— a real, built-in browser method purpose-built for exactly this scenario — it genuinely queues an asynchronous, non-blocking POST request that the browser guarantees to attempt sending even as the page is being torn down, without requiring the page to stay alive to await a response. - 📌 Interview term: the real, direct answer to the prompt — a normal
fetch()call made inside an unload-adjacent event handler is genuinely unreliable because the BROWSER may terminate the page's process before an in-flight, still-pending asynchronous request actually completes — there is no real guarantee an asyncfetch()Promise gets the chance to resolve once the page is gone. - 📌 Interview term: the real, verified synchronous-boolean behavior — verified directly:
sendBeacon()genuinely returns a real, synchronous boolean (trueif the browser successfully queued the request) IMMEDIATELY — confirmed directly, the call itself completed in a real, measured ~0.3ms — it is genuinely NOT a Promise and does NOT wait for any network response, which is exactly why it can safely be called from a handler that has almost no time left to run before the page disappears. - 📌 Interview term: the payload constraint — a precise answer names that
sendBeacon()is genuinely a fire-and-forget, one-way POST — the calling code genuinely has no way to read a response body, since by the time any response could arrive, the page that made the call may no longer exist. - A precise answer names the real, practical event to pair it with: the
"visibilitychange"event (checkingdocument.visibilityState === "hidden") or"pagehide"— both are genuinely more reliable unload-adjacent signals than the older"beforeunload"/"unload"events, which have real, known cross-browser inconsistencies, especially on mobile.
Clarifying questions expected:
- None — this is a definitional/practical question; directly answering the prompt's own "why is a normal fetch unreliable here" question with real, verified proof is the strong signal.
Code / implementation expected: Yes — a real sendBeacon() call, verified to return a synchronous boolean immediately, contrasted with the real, structural unreliability of an async fetch() in the same scenario.