aboutsummaryrefslogtreecommitdiff
path: root/static/js/refresh.ts
blob: 5d4485413e1be2b263d017204a3b4fdcbe593352 (plain)
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
(function () {
  function check(url, method, callback) {
    const http = new XMLHttpRequest();
    http.onreadystatechange = function () {
      if (http.readyState === 4 && http.status === 200) {
        if (callback) callback(http);
      }
    };
    http.open(method, url);
    http.setRequestHeader("Pragma", "no-cache");
    http.setRequestHeader("Cache-Control", "no-cache");
    http.send();
  }

  function update(id) {
    const url = self.location.href;
    check(url, "HEAD", function (request) {
      const local = document.querySelector('meta[name="last-modified"]').content;
      const remote = request.getResponseHeader("last-modified") || local;
      const localHour = local.substring(0, local.length - 9);
      const remoteHour = remote.substring(0, remote.length - 9);
      const modified = localHour !== remoteHour;

      if (modified) {
        const indicator = document.querySelector("a[data-update]");
        check(url, "GET");
        indicator.href = url;
        indicator.removeAttribute("id");
        indicator.dataset.update = "refresh";
        clearInterval(id);
      }
      console.log("R: " + remote);
      console.log("L: " + local);
      console.log("M: " + modified);
    });
  }

  self.addEventListener("load", function () {
    let meta = document.querySelector('meta[name="refresh"]');
    if (meta) meta = document.querySelector('meta[name="refresh"]').content;
    const interval = meta || 3600000;
    const monitor = setInterval(function () {
      if (navigator.onLine) update(monitor);
    }, interval);
  });
})();