-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclipboard.js
83 lines (69 loc) · 2.2 KB
/
clipboard.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
// Elements
const output = document.getElementById('output');
// Functions
function updateOutput(content) {
output.innerHTML = content;
}
function handleText(text) {
updateOutput(`Plain Text detected: <pre>${escapeHtml(text)}</pre>`);
}
function handleHTML(html) {
updateOutput(`HTML detected: <div>${html}</div>`);
}
function handleFiles(files) {
let outputHTML = 'Files detected: <ul>';
for (const file of files) {
outputHTML += `<li>${file.name} (Type: ${file.type}, Size: ${file.size} bytes)</li>`;
}
outputHTML += '</ul>';
updateOutput(outputHTML);
}
function handleImage(data) {
const image = new Image();
image.src = data;
image.onload = () => {
updateOutput(`Image detected: <img src="${data}" alt="Pasted Image" />`);
};
image.onerror = () => {
updateOutput(`Failed to load image.`);
};
}
function handleBinary(binaryData) {
updateOutput(`Binary detected: <pre>${escapeHtml(binaryData)}</pre>`);
}
function escapeHtml(text) {
return text.replace(/[&<>"']/g, (match) => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
})[match]);
}
function isBinary(text) {
return /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(text);
}
function isImage(text) {
const imagePattern = /\.(jpg|jpeg|png|gif|bmp|svg|webp|tiff|ico|heif|heic|apng|avif)$/i;
const base64Pattern = /^data:image\/(jpeg|png|gif|bmp|svg\+xml|tiff|ico|heif|heic|apng|avif);base64,/i;
return imagePattern.test(text) || base64Pattern.test(text);
}
// Events
document.getElementById('clipboardText').addEventListener('paste', (e) => {
e.preventDefault();
const clipboardData = e.clipboardData || window.clipboardData;
const pastedText = clipboardData.getData('Text');
const pastedHTML = clipboardData.getData('text/html');
const pastedFiles = clipboardData.files;
if (pastedFiles.length > 0) {
handleFiles(pastedFiles);
} else if (pastedHTML) {
handleHTML(pastedHTML);
} else if (isBinary(pastedText)) {
handleBinary(pastedText);
} else if (isImage(pastedText)) {
handleImage(pastedText);
} else {
handleText(pastedText);
}
});