Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML5 Server-Sent Events

HTML5 Server-Sent Events


HTML5 server-sent events allow web pages to get updates from the server.


Server-Sent Events - One-Way Messaging

Server-Sent events refer to web pages automatically getting updates from the server.

This was possible before, provided that the web page had to ask whether updates were available. With server-sent events, updates arrive automatically.

Examples: Facebook/Twitter updates, stock price updates, new blog posts, game results, etc.


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support server-sent events, except Internet Explorer.


Receiving Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:

Example

var

source

=

new

EventSource

(

"

demo_sse.php

"

)

;

source

.

onmessage

=

function

(

event

)

{

document

.

getElementById

(

"

result

"

)

.

innerHTML

+=

event

.

data

"


"

;

}

;

Try it »

Example analysis:


Detecting Server-Sent Event Support

In the following example, we have written some extra code to detect browser support for server-sent events:

if(typeof(EventSource)!=="undefined")

{

    // Browser supports Server-Sent

    // Some code.....

}

else

{

    // Browser does not support Server-Sent..

}


Server-Side Code Example

For the example above to work, you also need a server that can send data updates (such as PHP or ASP).

The syntax of the server-side event stream is very simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending the event stream.

Example

ASP Code (VB) (demo_sse.asp):

<%

Response.ContentType="text/event-stream"

Response.Expires=-1

Response.Write("data: " & now())

Response.Flush()

%>

Code explanation:


EventSource Object

In the example above, we used the onmessage event to get messages. However, other events can also be used:

Events Description
onopen When the connection to the server is opened
onmessage When a message is received
onerror When an error occurs