2

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

Nasiruddin Saiyed
  • 1,238
  • 1
  • 9
  • 24
  • To make this question actually answerable you need to find a way to show how data is organized in `$scope.result`. – wOxxOm Apr 02 '18 at 13:25
  • As for the second method, it may fail due to https://crbug.com/821219 broken in Chrome 65, so you may try it with chrome.downloads.download as in the first method, or use an iframe workaround shown in the second comment in the crbug link above. – wOxxOm Apr 02 '18 at 13:28

2 Answers2

2

try this

var csvData = new Blob(JSON.stringify($scope.result), { type: 'text/csv' }); 
var csvUrl = URL.createObjectURL(csvData);
chrome.downloads.download({ url: csvUrl });
1

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 });
Peter T.
  • 7,127
  • 3
  • 31
  • 30