Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventSource XHR headers

I'm trying to use EventSource for a streaming connection to a server. But I need to set a session key header on the underlying XHR request. How do I access the XHR from the EventSource object if it's even possible? Thanks!

Note that I'm not sure if CORS is even supported with EventStream yet, which would prevent this from working for me in the first place, but I've read in certain places that it should be supported...

like image 959
ionox0 Avatar asked Jun 17 '14 19:06

ionox0


People also ask

What is EventSource in Javascript?

The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling EventSource.

Which method of EventSource object will be invoked when an error occurs?

The onerror event occurs when an error occurs with the event source. An error usually occurs when a connection is disrupted. If this happens, the EventSource object will automatically attempt to reconnect to the server.

What is event source with example?

The local Business Monitor event source can be a producer or a consumer of events. For example, a remote application sends an event to the local REST XML event service.

Which type of component is introduced by SSE?

To meet this goal, SSE introduces two components: a new EventSource interface in the browser, which allows the client to receive push notifications from the server as DOM events, and the “event stream” data format, which is used to deliver the individual updates.


1 Answers

First, the good news is just about every browser supporting SSE also has CORS supported and working with it. (A year ago there were issues, so you will only hit problems if dealing with users who insist on running an out of date version of a modern auto-updating browser, which is an unusual combination.)

  • Now the bad news: you cannot set headers on EventSource requests. You will need to go back to good 'ole XHR streaming if you want to be able to set headers.

  • On the other hand, cookies are sent, so if your session information can be sent by cookie then that will work.

  • On the other other hand, cookies clash with CORS; so if you need both SSE and authentication with 3rd party sites you are going to be frustrated. You have to fallback to using XHR.

Apologies for the blatant plug, but the best source of information I know of, on both these topics, is chapter 9 of my book on SSE. It was the most difficult chapter to write :-).

like image 111
Darren Cook Avatar answered Oct 27 '22 06:10

Darren Cook