example-ws.html 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>ntfy.sh: WebSocket 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: WebSocket 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/WebSocket">WebSocket</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. <script type="text/javascript">
  23. const publishURL = `https://ntfy.sh/example`;
  24. const subscribeURL = `wss://ntfy.sh/example/ws`;
  25. const events = document.getElementById('events');
  26. const websocket = new WebSocket(subscribeURL);
  27. // Publish button
  28. document.getElementById("publishButton").onclick = () => {
  29. fetch(publishURL, {
  30. method: 'POST', // works with PUT as well, though that sends an OPTIONS request too!
  31. body: `It is ${new Date().toString()}. This is a test.`
  32. })
  33. };
  34. // Incoming events
  35. websocket.onopen = () => {
  36. let event = document.createElement('div');
  37. event.innerHTML = `WebSocket connected to ${subscribeURL}`;
  38. events.appendChild(event);
  39. };
  40. websocket.onerror = (e) => {
  41. let event = document.createElement('div');
  42. event.innerHTML = `WebSocket error: Failed to connect to ${subscribeURL}`;
  43. events.appendChild(event);
  44. };
  45. websocket.onmessage = (e) => {
  46. let event = document.createElement('div');
  47. event.innerHTML = e.data;
  48. events.appendChild(event);
  49. };
  50. </script>
  51. </body>
  52. </html>