-
Notifications
You must be signed in to change notification settings - Fork 3
/
content.js
577 lines (497 loc) · 19.7 KB
/
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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// --- Global Variables ---
let isBrowseButtonClicked = false;
let dragEnterCounter = 0;
let clipboardData = null;
let lastShowOverlayTime = 0;
const DEBOUNCE_DELAY = 200;
const originalStyles = {};
// --- Utility Functions ---
function createOverlay() {
const overlay = document.createElement('div');
overlay.id = 'custom-file-upload-overlay';
overlay.style.cssText = `
position: fixed; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(15, 17, 17, 0.7); display: flex;
justify-content: center; align-items: center; z-index: 10000;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
`;
const styleLink = document.createElement('link');
styleLink.rel = 'stylesheet';
styleLink.href = chrome.runtime.getURL('css/styles.css');
overlay.appendChild(styleLink);
return overlay;
}
function removeOverlay(overlay) {
if (overlay && overlay.parentNode) {
overlay.parentNode.removeChild(overlay);
}
}
function applyButtonStyles(button) {
button.style.cssText = `
padding: 16px 32px; margin: 0 10px; border: none; border-radius: 50px;
cursor: pointer; background: #085592; color: #e8e6e3; font-weight: 500;
transition: all 0.3s ease; font-size: 16px; text-transform: uppercase;
box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 6px, rgba(0, 0, 0, 0.08) 0px 1px 3px;
`;
button.addEventListener('mouseenter', () => {
button.style.transform = 'translateY(-2px)';
button.style.boxShadow = '0 7px 14px rgba(0, 0, 0, 0.12), 0 3px 6px rgba(0, 0, 0, 0.08)';
});
button.addEventListener('mouseleave', () => {
button.style.transform = 'translateY(0)';
button.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08)';
});
button.addEventListener('click', () => {
button.style.transform = 'translateY(1px)';
button.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06)';
});
}
function createImagePreviewElement() {
const imagePreview = document.createElement('img');
imagePreview.style.cssText = `
max-width: 100%; max-height: 400px; height: auto; border-radius: 10px;
object-fit: contain; margin-bottom: 30px; display: block; margin: 0 auto;
box-shadow: rgba(0, 0, 0, 0.1) 0px 15px 30px;
`;
return imagePreview;
}
function createTextLabelElement(text) {
const label = document.createElement('div');
label.textContent = text;
label.style.cssText = `
color: #c8c3bc; text-align: center; margin-bottom: 20px;
text-transform: uppercase; letter-spacing: 1px;
`;
return label;
}
function applyDragOverStyles(element) {
originalStyles.border = element.style.border;
originalStyles.backgroundColor = element.style.backgroundColor;
element.style.border = '3px dashed #2196F3';
element.style.backgroundColor = 'rgba(33, 150, 243, 0.1)';
element.style.transition = 'all 0.3s ease';
}
function removeDragOverStyles(element) {
element.style.border = originalStyles.border;
element.style.backgroundColor = originalStyles.backgroundColor;
}
function generateRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
function triggerDefaultFileDialog(inputElement) {
setTimeout(() => inputElement.click(), 100);
}
async function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const res = await fetch(dataurl);
return await res.blob();
}
// --- Overlay Functions ---
async function showCustomFileUploadOverlay(fileInput) {
const currentTime = Date.now();
if (currentTime - lastShowOverlayTime < DEBOUNCE_DELAY) {
return;
}
lastShowOverlayTime = currentTime;
if (isBrowseButtonClicked) {
isBrowseButtonClicked = false;
return;
}
let existingOverlay = document.getElementById('custom-file-upload-overlay');
if (existingOverlay) {
removeOverlay(existingOverlay);
}
existingOverlay = createOverlay();
document.body.appendChild(existingOverlay);
setupCloseOverlayEvents(existingOverlay);
const container = document.createElement('div');
container.style.cssText = `
padding: 40px; background-color: #0f1111; border-radius: 20px; text-align: center;
position: relative; overflow: hidden;
`;
const backgroundEffect = document.createElement('div');
backgroundEffect.style.cssText = `
position: absolute; top: -50%; left: -50%; width: 200%; height: 200%;
background: linear-gradient(45deg, #0a6ab6, #145ea8);
transform: rotate(-45deg); opacity: 0.1; z-index: -1;
`;
container.appendChild(backgroundEffect);
const imagePreview = createImagePreviewElement();
const imageLabel = createTextLabelElement("Image Preview");
imageLabel.style.color = '#c8c3bc';
imagePreview.style.display = 'none';
imageLabel.style.display = 'none';
container.append(imageLabel, imagePreview);
const pasteButton = document.createElement('button');
pasteButton.textContent = 'Paste File';
applyButtonStyles(pasteButton);
pasteButton.onclick = () => {
if (clipboardData) {
pasteFileIntoInput(fileInput, clipboardData);
}
};
pasteButton.style.display = 'none';
const browseButton = document.createElement('button');
browseButton.textContent = 'Browse Files';
applyButtonStyles(browseButton);
browseButton.onclick = () => {
isBrowseButtonClicked = true;
removeOverlay(existingOverlay);
triggerDefaultFileDialog(fileInput);
};
const buttonContainer = document.createElement('div');
buttonContainer.style.cssText = `
display: flex; justify-content: center; align-items: center; margin-top: 30px;
`;
fileInput.addEventListener('change', () => {
isBrowseButtonClicked = false;
clipboardData = null;
}, { once: true });
if (!clipboardData && !isBrowseButtonClicked) {
openClipboardHelper();
}
buttonContainer.appendChild(pasteButton);
buttonContainer.appendChild(browseButton);
const clipboardMessage = document.createElement('div');
clipboardMessage.style.cssText = `
color: #f54e42; text-align: center;
display: none; margin-bottom: 20px;
`;
clipboardMessage.textContent = 'Awaiting image from clipboard...';
container.appendChild(clipboardMessage);
container.append(buttonContainer);
existingOverlay.appendChild(container);
fadeInOverlay(existingOverlay);
setupDragAndDropEvents(container, fileInput, imagePreview);
existingOverlay.onclick = () => {
clipboardData = null;
removeOverlay(existingOverlay);
};
await new Promise(resolve => {
const checkClipboardData = () => {
if (clipboardData) {
resolve();
} else {
setTimeout(checkClipboardData, 100);
}
};
checkClipboardData();
});
if (clipboardData && (clipboardData.mimeType.startsWith('image/') || clipboardData.mimeType === 'text/plain')) {
pasteButton.style.display = 'inline-block';
} else {
pasteButton.style.display = 'none';
}
if (clipboardData && clipboardData.mimeType.startsWith('image/')) {
imagePreview.src = clipboardData.fileDataUrl;
imagePreview.style.display = 'block';
imageLabel.style.display = 'block';
} else {
imagePreview.style.display = 'none';
imageLabel.style.display = 'none';
}
}
function fadeInOverlay(overlay) {
overlay.style.opacity = '0';
setTimeout(() => {
overlay.style.transition = 'opacity 0.5s ease';
overlay.style.opacity = '1';
}, 0);
}
function setupCloseOverlayEvents(overlay) {
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
removeOverlay(overlay);
}
});
overlay.addEventListener('click', (event) => {
if (event.target === overlay) {
removeOverlay(overlay);
}
});
}
// --- Drag and Drop Functions ---
function setupDragAndDropEvents(container, fileInput, imagePreview) {
const handleDragEvents = (event, handler) => {
event.stopPropagation();
event.preventDefault();
handler(event, container);
};
const handleDrop = (event) => {
event.stopPropagation();
event.preventDefault();
dragEnterCounter = 0;
removeDragOverStyles(container);
const files = event.dataTransfer.files;
if (files.length > 0) {
prepareFilesForUpload(fileInput, files);
removeOverlay(document.getElementById('custom-file-upload-overlay'));
}
};
container.addEventListener('dragover', (event) => handleDragEvents(event, handleDragOver));
container.addEventListener('dragenter', (event) => handleDragEvents(event, handleDragEnter));
container.addEventListener('dragleave', (event) => handleDragEvents(event, handleDragLeave));
container.addEventListener('drop', (event) => handleDrop(event));
const buttons = container.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('dragover', (event) => handleDragEvents(event, handleDragOver));
button.addEventListener('dragenter', (event) => handleDragEvents(event, handleDragEnter));
button.addEventListener('dragleave', (event) => handleDragEvents(event, handleDragLeave));
button.addEventListener('drop', (event) => handleDrop(event));
});
}
function handleDragEnter(event, container) {
dragEnterCounter++;
if (dragEnterCounter === 1) {
applyDragOverStyles(container);
}
}
function handleDragLeave(event, container) {
dragEnterCounter--;
if (dragEnterCounter === 0) {
removeDragOverStyles(container);
}
}
function handleDragOver(event) {
event.dataTransfer.dropEffect = 'copy';
}
function prepareFilesForUpload(fileInput, files) {
const fileList = new DataTransfer();
for (const file of files) {
fileList.items.add(file);
}
fileInput.files = fileList.files;
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
}
// --- Clipboard Functions ---
function openClipboardHelper() {
chrome.runtime.sendMessage({ action: "openClipboardHelper" }, (response) => {
if (chrome.runtime.lastError) {
console.error("Error in openClipboardHelper:", chrome.runtime.lastError.message);
chrome.runtime.sendMessage({ closeTab: true });
}
});
}
async function pasteFileIntoInput(fileInput, data) {
try {
const blob = await dataURLtoBlob(data.fileDataUrl);
let fileExtension;
if (data.mimeType === 'image/webp') {
fileExtension = 'webp';
} else if (data.mimeType === 'text/plain') {
fileExtension = 'txt';
} else {
fileExtension = data.mimeType.split('/')[1] || 'bin';
}
const fileName = `pasted-file-${generateRandomString(6)}.${fileExtension}`;
const file = new File([blob], fileName, { type: data.mimeType });
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
fileInput.files = dataTransfer.files;
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
removeOverlay(document.getElementById('custom-file-upload-overlay'));
console.log('Uploaded file base64 URL:', data.fileDataUrl);
} catch (error) {
console.error("Error pasting file into input:", error);
}
}
// --- Event Handlers ---
function shouldPreventDefault(fileInput) {
return !isBrowseButtonClicked;
}
// --- Event Listeners ---
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.fileDataUrl && request.mimeType) {
clipboardData = {
fileDataUrl: request.fileDataUrl,
mimeType: request.mimeType
};
sendResponse({ success: true });
} else {
sendResponse({ success: false, error: 'No file data provided.' });
}
return true;
});
document.addEventListener('focusin', (event) => {
if (event.target.tagName.toLowerCase() === 'input' && event.target.type === 'file' && !event.target.hasAttribute('webkitdirectory')) {
console.debug('Focusin event:', event);
event.preventDefault();
showCustomFileUploadOverlay(event.target);
}
}, true);
document.addEventListener('paste', async (event) => {
const site = window.location.hostname;
const fileInput = document.querySelector('input[type="file"]:not([webkitdirectory])');
if (!fileInput) {
return;
}
chrome.runtime.sendMessage({ action: 'getSitePreference', site }, async (response) => {
const enabled = response.enabled;
if (enabled === undefined) {
const confirm = window.confirm('ClipboardToFileInput: Do you want to enable automatic pasting for this site? You can reset your preferences later by clicking the extension icon.');
chrome.runtime.sendMessage({ action: 'saveSitePreference', site, enabled: confirm });
if (!confirm) return;
} else if (!enabled) {
return;
}
const activeElement = document.activeElement;
if (activeElement.tagName.toLowerCase() === 'input' && activeElement.type === 'file') {
const result = await pasteFileIntoInput(activeElement);
if (result.success) {
event.preventDefault();
} else {
console.error(result.error);
}
} else if (fileInput) {
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
if (type.startsWith('image/')) {
const blob = await clipboardItem.getType(type);
const reader = new FileReader();
reader.onloadend = () => {
const dataUrl = reader.result;
pasteFileIntoInput(fileInput, { fileDataUrl: dataUrl, mimeType: type });
};
reader.readAsDataURL(blob);
return;
}
}
}
}
});
});
document.addEventListener("click", async (event) => {
const target = event.target;
if (target.tagName.toLowerCase() === 'input' && target.type === 'file') {
const fileInput = target;
if (isBrowseButtonClicked) {
isBrowseButtonClicked = false;
return;
}
event.preventDefault();
await showCustomFileUploadOverlay(fileInput);
}
});
function injectScriptIntoIframes() {
const iframes = document.querySelectorAll('iframe');
iframes.forEach(iframe => {
try {
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
if (iframeDocument) {
const script = iframeDocument.createElement('script');
script.src = chrome.runtime.getURL('content.js');
iframeDocument.head.appendChild(script);
}
} catch (e) {
console.error('Error injecting script into iframe:', e);
}
});
}
injectScriptIntoIframes();
const iframeObserver = new MutationObserver(() => {
injectScriptIntoIframes();
});
iframeObserver.observe(document.body, { childList: true, subtree: true });
function findFileInput(element) {
if (element.tagName.toLowerCase() === 'input' && element.type === 'file') {
return element;
}
if (element.tagName.toLowerCase() === 'label' && element.control && element.control.type === 'file') {
return element.control;
}
let currentElement = element;
while (currentElement) {
if (currentElement.tagName.toLowerCase() === 'label' && currentElement.control && currentElement.control.type === 'file') {
return currentElement.control;
}
currentElement = currentElement.parentElement;
}
const allFileInputs = document.querySelectorAll('input[type="file"]:not([webkitdirectory])');
for (const fileInput of allFileInputs) {
if (fileInput.offsetParent === null) {
return fileInput;
}
}
return null;
}
const fileInputSelector = 'input[type="file"]:not([webkitdirectory])';
function handleNewFileInput(fileInput) {
if (!fileInputWeakMap.has(fileInput)) {
const customFileUploadHandled = {
value: true,
writable: true
};
const showPickerOriginal = {
value: fileInput.showPicker,
writable: true
};
fileInputWeakMap.set(fileInput, {
customFileUploadHandled,
showPickerOriginal
});
fileInput.addEventListener('click', (event) => {
if (shouldPreventDefault(fileInput)) {
event.preventDefault();
showCustomFileUploadOverlay(fileInput).catch(error => {
console.error("Error in showCustomFileUploadOverlay:", error);
});
}
});
fileInput.addEventListener('paste', async (event) => {
try {
const result = await pasteFileIntoInput(fileInput);
if (result.success) {
event.preventDefault();
} else {
console.error(result.error);
}
} catch (error) {
console.error("Error in pasteFileIntoInput:", error);
}
});
fileInput.addEventListener('change', () => {
clipboardData = null;
});
}
}
Object.defineProperty(HTMLInputElement.prototype, 'showPicker', {
configurable: true,
enumerable: true,
writable: true,
value: function() {
if (this.type === 'file') {
showCustomFileUploadOverlay(this).catch(error => {
console.error("Error in showCustomFileUploadOverlay:", error);
});
} else if (typeof this.__showPickerOriginal === 'function') {
this.__showPickerOriginal();
}
}
});
if (!HTMLInputElement.prototype.__showPickerOriginal) {
HTMLInputElement.prototype.__showPickerOriginal = HTMLInputElement.prototype.showPicker;
}
const fileInputWeakMap = new WeakMap();
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if (node.matches(fileInputSelector)) {
handleNewFileInput(node);
}
const fileInputs = node.querySelectorAll ? node.querySelectorAll(fileInputSelector) : [];
fileInputs.forEach((fileInput) => {
handleNewFileInput(fileInput);
});
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });