简体   繁体   中英

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?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM