-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (62 loc) · 2.11 KB
/
index.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
// File input field
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
printFileElements(file);
});
// File Drop
const dropArea = document.defaultView;
dropArea.addEventListener("drop", (event) => {
event.preventDefault();
event.stopPropagation();
const file = event.dataTransfer.files[0];
printFileElements(file);
});
// Prevent default drag and drop behavior
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
dropArea.addEventListener(eventName, (event) => {
event.preventDefault();
event.stopPropagation();
});
});
const printFileElements = (file) => {
const reader = new FileReader();
reader.readAsText(file);
reader.addEventListener("load", () => {
const fileLinks = extractLinks(reader.result);
fileLinks.forEach((message) => {
const newElement = document.createElement("div");
createLink(newElement, message);
const fullChat = document.getElementById("full-chat");
fullChat.appendChild(newElement);
});
csvDownload(file.name, fileLinks);
});
};
const createLink = (element, message) => {
const a = document.createElement("a");
const linkText = document.createTextNode(message);
a.appendChild(linkText);
a.href = message;
element.appendChild(a);
};
function extractLinks(text) {
const urlRegex =
/([http]?s?:?\/?\/?[www]?\.?[^\s]+\.(com|org|edu|gov|uk|net|ca|de|jp|fr|au|us|ru|ch|it|nl|se|no|es|mil)[^\s]*)/gi;
return text.match(urlRegex);
}
const csvDownload = (name, links) => {
const csvButtonEl = document.createElement("button");
csvButtonEl.id = "csv-download";
csvButtonEl.innerHTML = "Download as CSV";
document.getElementById("extractor").append(csvButtonEl);
csvButtonEl.addEventListener("click", () => {
let blob = new Blob([links.join("\n")], { type: "text/csv" });
var fileURL = URL.createObjectURL(blob);
let link = document.createElement("a");
link.setAttribute("href", fileURL);
link.setAttribute("download", name + "_links.csv");
document.body.appendChild(link);
link.click();
});
};