Search code examples
javascriptangularjsgoogle-chrome-extensionexport-to-csv

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

  • 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 });