: nply/liveside

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 
57 
58 
59 
60 
61 
/**
 * @file liveside.js
 * @brief Browser client for liveside's Server-Sent Events reload stream.
 *
 * liveside client snippet.
 *
 * liveside serves this file itself, so the easiest way to use it is
 * an absolute script tag pointing at liveside's own port:
 *
 *   <script src="http://localhost:8081/liveside.js"></script>
 *
 * That's a cross-origin request, which is fine for a <script> tag (no
 * CORS preflight involved) and lets this snippet auto-detect where the
 * SSE stream lives from its own src URL. If you instead copy this file
 * into the site being served and load it same-origin, set
 * window.__RELOAD_PORT__ before this script runs so it knows where to
 * connect.
 */
(function () {
	/**
	 * Resolve the liveside server origin used for the EventSource connection.
	 *
	 * The script prefers an explicit window.__RELOAD_PORT__, then derives the
	 * origin from this script tag's src, and finally falls back to localhost:8081.
	 *
	 * @returns {string} Origin such as "http://localhost:8081".
	 */
	function resolveOrigin() {
		if (window.__RELOAD_PORT__) {
			return "http://" + location.hostname + ":" + window.__RELOAD_PORT__;
		}
		var script = document.currentScript;
		if (script && script.src) {
			var url = new URL(script.src);
			return url.protocol + "//" + url.host;
		}
		return "http://" + location.hostname + ":8081";
	}

	/**
	 * Open the SSE connection and schedule automatic reconnects on failure.
	 *
	 * A "reload" message from the server reloads the current page.
	 *
	 * @returns {void}
	 */
	function connect() {
		var es = new EventSource(resolveOrigin() + "/livereload");

		es.onmessage = function (evt) {
			if (evt.data === "reload") location.reload();
		};

		es.onerror = function () {
			es.close();
			setTimeout(connect, 1000);
		};
	}

	connect();
})();