-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackground.js
57 lines (48 loc) · 1.73 KB
/
background.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
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({
isActive: false,
downloadFolder: '',
orderImages: false,
currentImageNumber: 1
});
});
function padNumber(num) {
return num.toString().padStart(3, '0');
}
function getFileExtension(filename) {
const match = filename.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i);
return match ? match[0].toLowerCase() : '.jpg';
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "downloadImage") {
chrome.storage.local.get(['downloadFolder', 'orderImages', 'currentImageNumber'], async (data) => {
const folder = data.downloadFolder ? data.downloadFolder + '/' : '';
let filename = request.filename;
if (data.orderImages) {
const currentNum = data.currentImageNumber || 1;
const ext = getFileExtension(request.filename);
filename = `image_${padNumber(currentNum)}${ext}`;
// Increment counter for next download
await chrome.storage.local.set({
currentImageNumber: currentNum + 1
});
}
const downloadPath = folder + filename;
console.log('Downloading to:', downloadPath);
chrome.downloads.download({
url: request.imageUrl,
filename: downloadPath,
saveAs: false
}, (downloadId) => {
if (chrome.runtime.lastError) {
console.error('Download error:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError });
} else {
console.log('Download started:', downloadId);
sendResponse({ success: true, downloadId: downloadId });
}
});
});
return true;
}
});