How to receive Server Sent Events in browser with plain JavaScript

To receive Server Sent Event in browser with JavaScript, you have to create the EventSource instance first:

const source = new EventSource("//localhost:8080/sse");
source.onopen = e => console.log('on open', e);

With the onmessage listener, you can retrieve "unnamed" events:

source.onmessage = e => console.log(e);

To retrieve named events like e.g.:

: crud-events
event: crud-event
id: 1620555147023
data: {"httpMethod":"POST","path":"/","payload":{"message":"hello, mockend","id":"1620555147023"}} have to use an even listener named after the event:

source.addEventListener('crud-event', e => console.log('event received', e));

The source.onmessage does not fire for unnamed events.

The events in this screencast were sent with:


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments