example_eventsource_sse.html 1.7 KB

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