'How to convert Javascript array into CSV file and download it from Chrome Extension?
Hello i am new to Chrome Extension and developing it in angularjs and i am trying to convert array into csv file and download it from Chrome Extension.
i have tried by
var csvData = new Blob($scope.result, { type: 'text/csv' });
var csvUrl = URL.createObjectURL(csvData);
chrome.downloads.download({ url: csvUrl });
then another method i got from SO
var finalVal = '';
for (var i = 0; i < $scope.result.length; i++) {
var value = $scope.result[i];
for (var j = 0; j < value.length; j++) {
var innerValue = value[j]===null?'':value[j].toString();
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0)
result = '"' + result + '"';
if (j > 0)
finalVal += ',';
finalVal += result;
}
finalVal += '\n';
}
console.log(finalVal);
var download = document.getElementById('download');
download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(finalVal));
download.setAttribute('download', 'test.csv');
But both of them didnt work properly, i have following permission in manifest.json
permissions": [
"http://*/*",
"https://*/*",
"unlimitedStorage",
"contextMenus",
"cookies",
"tabs",
"notifications",
"activeTab",
"downloads",
"background"
]
while the first method download a file but it contains
[object Object][object Object][object Object]
I need to export my $scope.result into a csv file
Solution 1:[1]
try this //$scope.result is JavaScript array.
var csvData = new Blob(JSON.stringify($scope.result), { type: 'text/csv' });
var csvUrl = URL.createObjectURL(csvData);
chrome.downloads.download({ url: csvUrl });
Solution 2:[2]
You can achieve that using Blob object and Chrome downloads API. Here is an example
let data = [["x", "y"], [10, 20]];
let csvContent = data.map(row => row.join(",")).join("\n");
let csvBlob = new Blob([csvContent], { type: 'text/csv' });
let csvUrl = URL.createObjectURL(csvBlob);
chrome.downloads.download({ url: csvUrl });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Peter T. |