EventSource Polyfill

0.9.6 · abandoned · verified Wed Apr 22

eventsource-polyfill provides a robust client-side polyfill for the W3C EventSource API, enabling Server-Sent Events (SSE) functionality in web browsers that lack native support, particularly older environments like Internet Explorer 8+ and Android browser 2.1+. The package aims to bridge the compatibility gap, ensuring that web applications can leverage SSE streams consistently across diverse browser landscapes. While the project saw its last significant update with version 0.9.7 in 2017, which addressed a critical bug related to 'data' events, its release cadence has ceased, indicating an abandoned status. Developers should be aware it's designed exclusively for browser applications, modifying the global window.EventSource object, and will not receive further updates or new features.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to load the `eventsource-polyfill` and then establish and manage a Server-Sent Events (SSE) connection using the globally available `EventSource` constructor, including event handling and error management.

import 'eventsource-polyfill'; // Ensure polyfill is loaded

function setupEventSource() {
  if (typeof window === 'undefined' || typeof EventSource === 'undefined') {
    console.warn('EventSource is not available in this environment or not polyfilled.');
    return;
  }

  // Replace with your actual SSE endpoint
  const eventSourceUrl = 'https://example.com/stream'; // Or a mock API if running locally

  console.log(`Attempting to connect to EventSource at ${eventSourceUrl}`);
  const es = new EventSource(eventSourceUrl);

  es.onopen = () => {
    console.log('EventSource connection opened.');
  };

  es.onmessage = (event) => {
    console.log('Received message:', event.data);
    // You can parse JSON if your events are JSON strings
    try {
      const data = JSON.parse(event.data);
      console.log('Parsed JSON data:', data);
    } catch (e) {
      // Not JSON
    }
  };

  es.addEventListener('customEvent', (event: MessageEvent) => {
    console.log('Received custom event "customEvent":', event.data);
  });

  es.onerror = (error) => {
    console.error('EventSource error:', error);
    // Attempt to reconnect after a delay, or close if critical
    es.close();
    console.log('EventSource closed due to error. Reconnecting in 5 seconds...');
    setTimeout(setupEventSource, 5000);
  };

  // Close the connection after some time or based on user action
  setTimeout(() => {
    es.close();
    console.log('EventSource connection closed after 30 seconds.');
  }, 30000);
}

setupEventSource();

view raw JSON →