javascriptserver-sent-eventseventsource

SSE: 'onmessage' never gets called


I'm following the most simple tutorials on the internet about how to listen to Server-Sent Events from Javascript:

var es = new EventSource('url')
es.onmessage = function (e) { console.log(e.data) }

But my message handlers never get called. onopen and onerror handlers do get called, Chrome Developer Tools do show a nice "stream" view of the events being sent by the server and if I do the same call from curl I get a stream of events nicely formatted in the correct way. What could be wrong?


Solution

  • Just realized, from this tutorial, that you can associate an event name with each server-sent event.

    When you do that, the message listener stops getting called and instead you have to setup a new special listener for each kind of event you're sending. I was doing that on my server.

    So instead of es.onmessage = function () {...} I had to do es.addEventListener("special-event-name", function () {...}).