-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinsert-content.js
45 lines (38 loc) · 1.21 KB
/
insert-content.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
// Inject content from another URL specified within a comment block on the requested page.
// e.g.
// <!-- include https://www.google.co.uk -->
addEventListener("fetch", (event) => {
event.respondWith(main(event));
});
async function main(event) {
const response = await fetch(event.request);
return insertContent(response);
}
class DocumentHandler {
constructor(response) {
this.response = response;
}
async comments(comment) {
const [directive, url] = comment.text.trim().split(" ");
let fetchUrl;
// Determine if the specified URL is relative or absolute
if (url.indexOf("://") > 0 || url.indexOf("//") === 0) {
fetchUrl = new URL(url);
} else {
// Create a URL object using the origin from the original response
// to create an absolute URL
const responseUrl = new URL(this.response.url);
fetchUrl = new URL(responseUrl.origin);
fetchUrl.pathname = url;
}
if (directive === "include") {
const response = await fetch(fetchUrl.href);
comment.replace(await response.text(), { html: true });
}
}
}
function insertContent(response) {
return new HTMLRewriter()
.onDocument(new DocumentHandler(response))
.transform(response);
}