Debian Codegraph @

examples/web-example-eventsource/example-sse.html

raw
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>ntfy.sh: EventSource Example</title>
6 <meta name="robots" content="noindex, nofollow" />
7 <style>
8 body { font-size: 1.2em; line-height: 130%; }
9 #events { font-family: monospace; }
10 </style>
11 </head>
12 <body>
13 <h1>ntfy.sh: EventSource Example</h1>
14 <p>
15 This is an example showing how to use <a href="https://ntfy.sh">ntfy.sh</a> with
16 <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource</a>.<br/>
17 This example doesn't need a server. You can just save the HTML page and run it from anywhere.
18 </p>
19 <button id="publishButton">Send test notification</button>
20 <p><b>Log:</b></p>
21 <div id="events"></div>
22
23 <script type="text/javascript">
24 const publishURL = `https://ntfy.sh/example`;
25 const subscribeURL = `https://ntfy.sh/example/sse`;
26 const events = document.getElementById('events');
27 const eventSource = new EventSource(subscribeURL);
28
29 // Publish button
30 document.getElementById("publishButton").onclick = () => {
31 fetch(publishURL, {
32 method: 'POST', // works with PUT as well, though that sends an OPTIONS request too!
33 body: `It is ${new Date().toString()}. This is a test.`
34 })
35 };
36
37 // Incoming events
38 eventSource.onopen = () => {
39 let event = document.createElement('div');
40 event.innerHTML = `EventSource connected to ${subscribeURL}`;
41 events.appendChild(event);
42 };
43 eventSource.onerror = (e) => {
44 let event = document.createElement('div');
45 event.innerHTML = `EventSource error: Failed to connect to ${subscribeURL}`;
46 events.appendChild(event);
47 };
48 eventSource.onmessage = (e) => {
49 let event = document.createElement('div');
50 event.innerHTML = e.data;
51 events.appendChild(event);
52 };
53 </script>
54
55 </body>
56 </html>