codegurukool.com · Free coding tutorials & online compiler

Home › HTML Tutorial › Server-sent events API

Server-sent events API

Receive live updates from a server.

EventSource keeps a connection open so a server can push messages. It needs a real server endpoint, so this is a pattern to copy rather than run here.

Example code

<p id='o'>Waiting...</p>
<script>
// Needs a server that sends text/event-stream
try{
const s=new EventSource('/updates');
s.onmessage=e=>o.textContent=e.data;
s.onerror=()=>o.textContent='No server at /updates';
}catch(e){o.textContent=e.name}
</script>

Run this code in the online editor

← Web workers APILive project: Personal profile page →