3

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?

fiatjaf
  • 11,479
  • 5
  • 56
  • 72

2 Answers2

4

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 () {...}).

fiatjaf
  • 11,479
  • 5
  • 56
  • 72
1

Here is a minimal example showing how you can get the default message event type and a custom event type on the same SSE stream.

<html lang="en">
  <body>
    <div id="payload"></div>
    <script>

      const stream = new EventSource('https://url-goes-here');

      stream.addEventListener('message', (event) => {
        document.getElementById('payload').innerText = `Received a regular message: ${event.data}`;
      }, false);

      stream.addEventListener('myEvent', (event) => {
        document.getElementById('payload').innerText = `Received a myEvent message: ${event.data}`;
      }, false);

    </script>
  </body>
</html>
Robin Zimmermann
  • 3,441
  • 1
  • 22
  • 15
  • I tried that much before creating this question, it didn't work. – fiatjaf Dec 18 '19 at 02:20
  • 1
    Now I realized you're talking about different messages in the same stream! Then it could work. But if your message is tagged as `myEvent` then it won't be handled by `onmessage`. – fiatjaf Dec 18 '19 at 02:21
  • Ah, now I see what you mean. No, `onmessage` only handles the default message type `message`. That's why you add an event listener explicitly for the event types you care about. – Robin Zimmermann Dec 18 '19 at 02:50