-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
38 lines (34 loc) · 1.4 KB
/
Copy pathbackground.js
File metadata and controls
38 lines (34 loc) · 1.4 KB
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
// Background script to handle downloads
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'downloadCSV') {
// Handle the download asynchronously
handleDownload(request, sendResponse);
return true; // Keep message channel open for async response
}
});
async function handleDownload(request, sendResponse) {
try {
// Convert CSV data to base64 data URL
const csvData = request.csvData;
const base64Data = btoa(unescape(encodeURIComponent(csvData)));
const dataUrl = `data:text/csv;charset=utf-8;base64,${base64Data}`;
const downloadId = await new Promise((resolve, reject) => {
chrome.downloads.download({
url: dataUrl,
filename: request.filename,
saveAs: false // Set to true if you want to show save dialog
}, (downloadId) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(downloadId);
}
});
});
console.log('Download started with ID:', downloadId);
sendResponse({success: true, downloadId: downloadId});
} catch (error) {
console.error('Download failed:', error);
sendResponse({success: false, error: error.message});
}
}