28

I'm using SSE with the EventStream built in logic for javascript. While having onopen return a successful result the onmessage callback is not working. Odd thing here is that within Chrome in the EventStream tab the data results are listed as I expect them.

This is my JS snippet for the EventSource

var eventSource;
  $(function () {
    eventSource  = new EventSource('get/status/');

    eventSource.onopen = function () {
      console.log("Sse connection opened");
    };

    eventSource.onerror = function () {
      console.log("error occured");
    };

    eventSource.onmessage = function (event) {
      console.log("received");
    };

  });

enter image description here

As you can see there is data being emitted but onmessage is never triggered. Can anybody explain this behaviour to me?

EDIT: onopen and onerror do both work.

xetra11
  • 7,671
  • 14
  • 84
  • 159

1 Answers1

46

According to the screenshot, your event-stream contains events of type "foo", not "message". That is only the default type (absent an event field in the event-stream). From the spec:

  1. Initialize event's type attribute to message, […]

  2. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal the value of the event type buffer.

Here, you should set your listener to listen for "foo" events:

eventSource.addEventListener("foo", function() {...})
Touffy
  • 6,309
  • 22
  • 28
  • FYI: If you are using Spring's SSE support and are returning a SseEmitter object, the 'type' attribute seems to correspond to what you pass to SseEventBuilder.name() – Spence7 Jan 11 '22 at 03:40
  • Sometimes even five year old answers solve today's problems. Been banging my head against this for a few hours now. Changing server side to output event: message solved it. Many thanks. – Christopher Sep 09 '22 at 08:26
  • Well, EventSource is 15 years old after all… BTW you could just omit the event type in the stream to get the same result, since "message" is the default. – Touffy Sep 10 '22 at 09:40