MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Crash Reporting & Telemetry Buffering0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
16.1Performance API (performance.mark & measure)16.2Logging Architecture & Structured Log Levels16.3Integrating Error Tracking (Sentry/Monitoring Concepts)16.4Crash Reporting & Telemetry Buffering
HomeTutorialsJavaScript for AdvancedCrash Reporting & Telemetry Buffering
Proxy & Reflect API Deep Dive

Crash Reporting & Telemetry Buffering

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Transmitting analytics events and crash telemetry to remote monitoring servers on every single user interaction creates high network overhead and drains mobile batteries. Conversely, sending telemetry when the user closes a tab often fails because standard fetch() calls are abruptly aborted. Telemetry Buffering and navigator.sendBeacon() solve both problems.


1. The Page Unload Problem

Historically, developers attempted to send telemetry during window.onbeforeunload or window.onunload:

1// ANTI-PATTERN: Fails on modern browsers!
2window.addEventListener('unload', () => {
3 // fetch() is CANCELLED immediately when the tab closes!
4 fetch('/analytics', { method: 'POST', body: JSON.stringify(metrics) });
5});

Because the tab is being terminated, the browser terminates all active HTTP connections, and the telemetry is lost.


2. The Solution: navigator.sendBeacon()

navigator.sendBeacon(url, data) sends small amounts of data asynchronously over HTTP POST. The browser guarantees that the data is transmitted to the server, even after the page has finished closing!

1window.addEventListener('visibilitychange', () => {
2 if (document.visibilityState === 'hidden') {
3 const payload = JSON.stringify(bufferedEvents);
4 const blob = new Blob([payload], { type: 'application/json' });
5 
6 // Browser schedules background transmission that survives tab closing!
7 const success = navigator.sendBeacon('/api/telemetry', blob);
8 if (success) {
9 bufferedEvents = []; // Cleared successfully
10 }
11 }
12});
Use the visibilitychange event rather than unload or beforeunload. Mobile browsers frequently suspend background tabs without firing unload!

3. The fetch() with keepalive: true Alternative

Modern Fetch API supports keepalive: true, which keeps the HTTP request alive after the page is discarded:

1function sendFinalAnalytics(data) {
2 fetch('/api/telemetry', {
3 method: 'POST',
4 headers: { 'Content-Type': 'application/json' },
5 body: JSON.stringify(data),
6 keepalive: true // Keeps connection alive even if tab closes!
7 });
8}

4. Implementing a Production Telemetry Buffer

To avoid spamming analytics endpoints with hundreds of tiny HTTP calls, buffer events in memory and flush them in batches based on buffer size or a periodic timer:

1class TelemetryBuffer {
2 constructor(endpoint, maxBufferSize = 20, flushIntervalMs = 5000) {
3 this.endpoint = endpoint;
4 this.maxBufferSize = maxBufferSize;
5 this.flushIntervalMs = flushIntervalMs;
6 this.buffer = [];
7 
8 // Periodic flush timer
9 this.timer = setInterval(() => this.flush(), this.flushIntervalMs);
10 
11 // Flush on page hidden / unload
12 document.addEventListener('visibilitychange', () => {
13 if (document.visibilityState === 'hidden') {
14 this.flush();
15 }
16 });
17 }
18 
19 track(eventName, properties = {}) {
20 this.buffer.push({
21 event: eventName,
22 properties,
23 timestamp: Date.now()
24 });
25 
26 // Flush immediately if buffer reaches capacity threshold
27 if (this.buffer.length >= this.maxBufferSize) {
28 this.flush();
29 }
30 }
31 
32 flush() {
33 if (this.buffer.length === 0) return;
34 
35 const payload = JSON.stringify(this.buffer);
36 this.buffer = []; // Clear buffer immediately to prevent duplicate sends
37 
38 // Attempt sendBeacon first, fallback to fetch with keepalive
39 if (navigator.sendBeacon) {
40 const blob = new Blob([payload], { type: 'application/json' });
41 navigator.sendBeacon(this.endpoint, blob);
42 } else {
43 fetch(this.endpoint, {
44 method: 'POST',
45 headers: { 'Content-Type': 'application/json' },
46 body: payload,
47 keepalive: true
48 }).catch(err => console.warn('Telemetry flush failed:', err));
49 }
50 }
51}
52 
53// Global instance
54export const analytics = new TelemetryBuffer('/api/v1/telemetry');

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why do standard fetch() requests often fail when initiated inside a window 'unload' event?
Question 2
What is the primary guarantee of navigator.sendBeacon(url, data)?
Question 3
Which page lifecycle event is the recommended modern replacement for 'unload' and 'beforeunload' when saving state and flushing telemetry?
Question 4
What fetch() option keeps an HTTP request alive after a page unloads, serving as an alternative to sendBeacon?
Question 5
What is the primary operational benefit of Telemetry Buffering?
Next Lesson

Proxy & Reflect API Deep Dive

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Integrating Error Tracking (Sentry/Monitoring Concepts)Proxy & Reflect API Deep Dive

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext