Table of Contents
Enable SSE in JavaScript
Set Up the Server Response
Handle Connection States and Reconnection
Home Web Front-end H5 Tutorial How to use server-sent events (SSE) in HTML5?

How to use server-sent events (SSE) in HTML5?

Sep 21, 2025 am 06:11 AM
html5 sse

SSE enables real-time, unidirectional server-to-client updates via HTTP; use EventSource in JavaScript to connect, handle messages with onmessage, set server response type to text/event-stream, format data with "data:" and "\n\n", and optionally include event IDs for reconnection.

How to use server-sent events (SSE) in HTML5?

Server-Sent Events (SSE) in HTML5 allow a web page to get automatic updates from a server without polling. This is useful when you need real-time data like live feeds, notifications, or stock prices. Unlike WebSockets, SSE is unidirectional—data flows from server to client—and it works over standard HTTP.

Enable SSE in JavaScript

To use SSE, create an EventSource object in your JavaScript code. Pass the URL of the server endpoint that sends event data.

  • Create a new EventSource instance with the server URL
  • Listen for incoming messages using the onmessage handler
  • Optionally handle errors with onerror

Example:

<code>if (typeof EventSource !== "undefined") {
  const source = new EventSource("/sse-updates");
  
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML  = event.data   "<br>";
  };

  source.onerror = function() {
    console.log("EventSource failed.");
  };
} else {
  document.getElementById("result").innerHTML = "SSE not supported";
}
</code>

Set Up the Server Response

The server must send data using a specific format and set the correct MIME type: text/event-stream.

  • Response content type should be text/event-stream
  • Data lines start with data: followed by the message
  • End each message with two newline characters (\n\n)
  • Optional: include id: for reconnection tracking or retry: for retry interval

Example server response (Node.js/Express):

<code>app.get('/sse-updates', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  setInterval(() => {
    res.write(`data: ${new Date().toISOString()}\n\n`);
  }, 1000);
});
</code>

Handle Connection States and Reconnection

SSE automatically tries to reconnect if the connection drops. The browser uses the last seen event ID to resume from where it left off—if the server supports it.

  • Send an id: field with each event so the server can track position
  • Use source.close() to manually stop listening
  • Monitor readyState: 0 (connecting), 1 (open), 2 (closed)

Example with event ID:

<code>res.write(`id: ${eventId}\ndata: Hello\n\n`);
</code>

Basically, just set up the client with EventSource, configure your server to stream properly formatted events, and handle messages as they arrive. It's simple, built on HTTP, and widely supported.

The above is the detailed content of How to use server-sent events (SSE) in HTML5?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to manage focus for accessibility in HTML5? How to manage focus for accessibility in HTML5? Sep 21, 2025 am 05:27 AM

UsesemanticHTMLelementslikeandfornativefocusabilityandkeyboardsupport.EnsurelogicaltaborderandvisiblefocusindicatorsviaCSS.Programmaticallymanagefocusindynamiccontentlikemodalsusingelement.focus(),trappingfocusinsideandreturningitafterclosure.ApplyAR

How to use server-sent events (SSE) in HTML5? How to use server-sent events (SSE) in HTML5? Sep 21, 2025 am 06:11 AM

SSEenablesreal-time,unidirectionalserver-to-clientupdatesviaHTTP;useEventSourceinJavaScripttoconnect,handlemessageswithonmessage,setserverresponsetypetotext/event-stream,formatdatawith"data:"and"\n\n",andoptionallyincludeeventIDsf

How to properly use the  element in HTML5? How to properly use the element in HTML5? Sep 17, 2025 am 06:33 AM

ThetimeelementinHTML5representsdatesandtimesinamachine-readableformat,enhancingaccessibilityandSEO;usethedatetimeattributewithISO-formattedvaluestoprovidesemanticmeaning,especiallyforhuman-friendlytextordurations,ensuringconsistentinterpretationbymac

How to use ARIA roles for accessibility in HTML5? How to use ARIA roles for accessibility in HTML5? Sep 21, 2025 am 04:41 AM

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

How to validate a form field against a regular expression in HTML5? How to validate a form field against a regular expression in HTML5? Sep 22, 2025 am 05:11 AM

UsethepatternattributeinHTML5inputelementstovalidateagainstaregex,suchasforpasswordsrequiringnumbers,uppercase,lowercase,andminimumlength;pairwithtitleforuserguidanceandrequiredfornon-emptyenforcement.

How to embed an SVG file directly into an HTML5 document? How to embed an SVG file directly into an HTML5 document? Sep 17, 2025 am 04:49 AM

To embed SVG directly, insert the SVG code into the HTML tag to remove the XML declaration. 2. Copy the SVG content and paste it into HTML, such as an example containing a circle. 3. Advantages include CSS style control, JavaScript operations, reduction of HTTP requests and responsive support. 4. Redundant properties can be cleaned up and the necessary namespace can be retained.

How to set the viewport for mobile devices in HTML5? How to set the viewport for mobile devices in HTML5? Sep 16, 2025 am 02:28 AM

Adding a viewport meta tag ensures that web pages are displayed correctly on mobile devices, preventing browsers from rendering at desktop width by default and shrinking the page.

How to animate SVG paths in an HTML5 document? How to animate SVG paths in an HTML5 document? Sep 21, 2025 am 01:58 AM

UseCSSstroke-dasharrayandstroke-dashoffsetforsimpledrawinganimations;2.ApplyJavaScriptfordynamictriggerslikeloadorscroll;3.EmploylibrarieslikeGSAPforpathmorphing;4.Optimizeperformancebylimitingconcurrentanimations.

See all articles