v2 / examples / veb / server_sent_events / index.html
38 lines · 38 sloc · 1.41 KB · 8683e634eec7625bfe2db10020e729a4eef9ec06
Raw
1<html>
2 <head>
3 <title>@title</title>
4 <meta charset="utf-8"/>
5 @css 'assets/site.css'
6 </head>
7 <body>
8 <h1>@title</h1>
9 <button>Close the connection</button>
10 <ul></ul>
11 <script>
12 "use strict";
13 var button = document.querySelector('button');
14 var eventList = document.querySelector('ul');
15 const evtSource = new EventSource('/sse');
16 evtSource.onerror = function() { console.log("EventSource failed."); };
17 console.log(evtSource.withCredentials);
18 console.log(evtSource.readyState);
19 console.log(evtSource.url);
20 evtSource.onopen = function() {
21 console.log("Connection to server opened.");
22 };
23 evtSource.onmessage = function(e) {
24 var newElement = document.createElement("li");
25 newElement.textContent = "message: " + e.data;
26 eventList.appendChild(newElement);
27 };
28 evtSource.addEventListener("ping", function(e) {
29 console.log(e)
30 var newElement = document.createElement("li");
31 var obj = JSON.parse(e.data);
32 newElement.innerHTML = "ping at " + obj.time + ' server data: ' + e.data;
33 eventList.appendChild(newElement);
34 }, false);
35 button.onclick = function() { console.log('Connection closed'); evtSource.close(); };
36 </script>
37 </body>
38</html>
39