File: example-sse.html

package info (click to toggle)
ntfy 2.11.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 19,364 kB
  • sloc: javascript: 16,782; makefile: 282; sh: 105; php: 21; python: 19
file content (56 lines) | stat: -rw-r--r-- 1,906 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ntfy.sh: EventSource Example</title>
    <meta name="robots" content="noindex, nofollow" />
    <style>
        body { font-size: 1.2em; line-height: 130%; }
        #events { font-family: monospace; }
    </style>
</head>
<body>
<h1>ntfy.sh: EventSource Example</h1>
<p>
    This is an example showing how to use <a href="https://ntfy.sh">ntfy.sh</a> with
    <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource</a>.<br/>
    This example doesn't need a server. You can just save the HTML page and run it from anywhere.
</p>
<button id="publishButton">Send test notification</button>
<p><b>Log:</b></p>
<div id="events"></div>

<script type="text/javascript">
    const publishURL = `https://ntfy.sh/example`;
    const subscribeURL = `https://ntfy.sh/example/sse`;
    const events = document.getElementById('events');
    const eventSource = new EventSource(subscribeURL);

    // Publish button
    document.getElementById("publishButton").onclick = () => {
        fetch(publishURL, {
            method: 'POST', // works with PUT as well, though that sends an OPTIONS request too!
            body: `It is ${new Date().toString()}. This is a test.`
        })
    };

    // Incoming events
    eventSource.onopen = () => {
        let event = document.createElement('div');
        event.innerHTML = `EventSource connected to ${subscribeURL}`;
        events.appendChild(event);
    };
    eventSource.onerror = (e) => {
        let event = document.createElement('div');
        event.innerHTML = `EventSource error: Failed to connect to ${subscribeURL}`;
        events.appendChild(event);
    };
    eventSource.onmessage = (e) => {
        let event = document.createElement('div');
        event.innerHTML = e.data;
        events.appendChild(event);
    };
</script>

</body>
</html>