-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebxdc-download-polyfill.js
More file actions
67 lines (62 loc) · 1.82 KB
/
webxdc-download-polyfill.js
File metadata and controls
67 lines (62 loc) · 1.82 KB
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
(() => {
const originalAnchorClick = HTMLAnchorElement.prototype.click;
HTMLAnchorElement.prototype.click = function () {
if (
!this.hasAttribute("download") ||
!this.href ||
document.contains(this)
) {
return originalAnchorClick.call(this);
}
const urlObj = new URL(this.href);
if (
!(
this.href.startsWith("blob:") ||
this.href.startsWith("data:") ||
urlObj.origin === location.origin
)
) {
return originalAnchorClick.call(this);
}
exportFileFromUrl(this.href, this.download);
};
document.addEventListener("click", (event) => {
const link = event.target.closest("a[download]");
if (!link || !link.href) return;
if (link.href.startsWith("blob:") || link.href.startsWith("data:")) {
event.preventDefault();
} else {
const urlObj = new URL(link.href);
if (urlObj.origin === location.origin) {
event.preventDefault();
} else return;
}
exportFileFromUrl(link.href, link.download);
});
async function exportFileFromUrl(url, name) {
const message = {
file: {},
};
if (url.startsWith("blob:")) {
const blob = await (await fetch(url)).blob();
message.file.blob = blob;
} else if (url.startsWith("data:")) {
const [meta, encoded] = url.split(",");
const isBase64 = meta.endsWith(";base64");
if (isBase64) {
message.file.base64 = encoded;
} else {
message.file.plainText = decodeURIComponent(encoded);
}
} else {
const blob = await (await fetch(url)).blob();
message.file.blob = blob;
if (!name) {
const urlObj = new URL(url);
name = urlObj.pathname.split("?")[0].split("/").pop();
}
}
message.file.name = name || "file";
window.webxdc.sendToChat(message);
}
})();