example_eventsource_sse.html 1.7 KB

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