-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
99 lines (78 loc) · 2.44 KB
/
main.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
const BASEURL = "https://icon.horse/icon";
class IconSearcher {
constructor(form, input, icon, website, iconLink, download) {
this.form = document.getElementById(form);
this.websiteInput = document.getElementById(input);
this.iconImage = document.getElementById(icon);
this.domainName = document.getElementById(website);
this.iconLink = document.getElementById(iconLink);
this.downloadIcon = document.getElementById(download);
this.setupEventListners();
}
setupEventListners() {
this.form.addEventListener("submit", (e) => this.handleSubmit(e));
this.downloadIcon.addEventListener("click", () => this.downloadFile());
}
// handles form sumbit
handleSubmit(e) {
e.preventDefault();
// get input value
const websiteVal = this.websiteInput.value.trim();
// if input value is empty
if (!websiteVal) return;
else this.searchIcon(websiteVal);
}
// search for the icon based on domain name
async searchIcon(domainName) {
const url = `${BASEURL}/${domainName}`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error("Network response was not ok!");
// console.log(response);
// console.log(response.url);
this.displayIcon(response.url);
} catch (error) {
console.log("Error:", error);
}
}
// display the icon
displayIcon(data) {
// set the source to the url
this.iconImage.src = data;
this.iconImage.alt = `Icon for ${this.websiteInput.value}`;
this.domainName.textContent = this.websiteInput.value;
// can click on icon for preview
this.iconLink.href = this.iconImage.src;
// reset values
this.websiteInput.value = "";
}
// download icon to device
async downloadFile() {
// fetch the file
try {
const response = await fetch(this.iconImage.src);
if (!response.ok) throw new Error("Network response was not ok!");
// handle binary data
const data = await response.blob();
const url = window.URL.createObjectURL(data);
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = "Icon";
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.log("Error:", error);
}
}
}
const icon = new IconSearcher(
"form",
"website-domain",
"icon",
"website",
"icon-link",
"download"
);