-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml-enhancer-ajax.js
99 lines (84 loc) · 2.63 KB
/
html-enhancer-ajax.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"use strict";
const AJAX_HEADERS = { "X-Requested-With": "XMLHttpRequest" };
// AJAX replacement
document.addEventListener("submit", async event => {
const submitter = event.submitter;
const form = event.target;
if (!form.matches("form[data-ajax-replace]")) return;
// Get form data.
const method = submitter.formmethod || form.method;
const url = new URL(submitter.formAction || form.action);
const formData = new FormData(form);
let options = {};
if (method === "post") {
options = { method: "POST", body: formData };
} else {
url.search = new URLSearchParams(formData);
}
// Fetch the HTML.
let html;
try {
options.headers = AJAX_HEADERS;
const response = await fetch(url, options);
if (!response.ok) throw new Error();
html = await response.text();
} catch (error) {
return;
}
// Insert the HTML.
const tmp = document.createElement("div");
tmp.innerHTML = html;
const container = document.getElementById(form.dataset.ajaxReplace);
container.replaceChildren(...tmp.children);
container.scrollIntoView();
// Update the URL.
history.replaceState({ replace: form.dataset.ajaxReplace }, null, url);
// Prevent form submission.
event.preventDefault();
});
document.addEventListener("click", async event => {
const anchor = event.target;
if (!anchor.matches("a[data-ajax-replace]")) return;
const url = anchor.href;
// Fetch the HTML.
let html;
try {
const response = await fetch(url, { headers: AJAX_HEADERS });
if (!response.ok) throw new Error();
html = await response.text();
} catch (error) {
return;
}
// Insert the HTML.
const tmp = document.createElement("div");
tmp.innerHTML = html;
const container = document.getElementById(anchor.dataset.ajaxReplace);
container.replaceChildren(...tmp.children);
container.scrollIntoView();
// Update the URL.
history.pushState({ replace: anchor.dataset.ajaxReplace }, null, url);
// Prevent following the link.
event.preventDefault();
});
window.addEventListener("popstate", async event => {
const url = event.target.location.href;
if (!event.state.replace) return;
// Fetch the HTML.
let html;
try {
const response = await fetch(url, {
headers: { "X-Requested-With": "XMLHttpRequest" },
});
if (!response.ok) throw new Error();
html = await response.text();
} catch (error) {
window.location.replace(url);
return;
}
// Insert the HTML.
const tmp = document.createElement("div");
tmp.innerHTML = html;
const container = document.getElementById(event.state.replace);
container.replaceChildren(...tmp.children);
container.scrollIntoView();
});