aboutsummaryrefslogtreecommitdiffstats
path: root/browser/static/htmp.js
blob: 62956a4b42b29ac6b6cbdae996c572305b29331f (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
const iframe = document.createElement("iframe");
iframe.name = "htmp";
iframe.hidden = true;
document.body.appendChild(iframe);

document
  .querySelector("iframe[name='htmp']")
  .addEventListener("load", function () {
    setTimeout(() => {
      const cd = this.contentDocument;
      const cw = this.contentWindow;
      // If the server responds with an entire HTML document, replace the current document with it.
      // To check whether the response is an entire page we check the presence of this very snippet.
      if (cd.querySelector("iframe[name='htmp']")) {
        document.documentElement.replaceWith(cd.documentElement);
        // If the server responds with a fragment, replace the target element with it.
      } else {
        document
          .querySelector(cw.location.hash || null)
          ?.replaceWith(...cd.body.childNodes);
        const url = new URL(cw.location.href);
        url.searchParams.delete("htmp");
        url.hash = "";
        history.replaceState({}, "", url.toString());
      }
    });
  });

document.querySelectorAll("form[htmp]").forEach(function (el) {
  const re = el.attributes.replace.value;
  const input = document.createElement("input");
  input.type = "hidden";
  input.name = "htmp";
  input.value = re;
  el.appendChild(input);

  const action = new URL(el.action);
  action.hash = re;
  el.action = action.toString();
  el.target = "htmp";
});