0

I have created a Shiny app that outputs data in a data table. As the data table contains dropdown menus that are injected, the default download button of Shiny and datatable do not work (either outputs all, including all dropdown menu options, or outputs HTML). I am trying to use Javascript to export the data that I have. For that I am using the following external Javascript function downloadcsv.js that I have created based on the following guide:

shinyjs.myfunction = function(args) {
    var data, filename, link, result, ctr, keys, columnDelimiter, lineDelimiter;

    columnDelimiter = ',';
    lineDelimiter = '\n';

    keys = Object.keys(data[0]);

    result = '';
    result += keys.join(columnDelimiter);
    result += lineDelimiter;

    data.forEach(function(item) {
        ctr = 0;
        keys.forEach(function(key) {
            if (ctr > 0) result += columnDelimiter;

            result += item[key];
            ctr++;
        });
        result += lineDelimiter;
    });

    csv = result;

    filename = 'export.csv';

    if (!csv.match(/^data:text\/csv/i)) {
        csv = 'data:text/csv;charset=utf-8,' + csv;
    }
    data = encodeURI(csv);

    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    link.click();
}

In ui.R of my Shiny app I have added a download button using:

  shinyjs::useShinyjs(),
  extendShinyjs(script = "downloadcsv.js"),
  actionButton("download", "Download"),

In server.R I have added:

onclick("download", js$myfunction(data))

However, when clicking the Download button, nothing happens. Running Shiny in a browser or in a window in RStudio does not make a difference. It seems that the link.click(); line is not executed, or that the download link is not created at all. The output in the console is as follows when running the app with shiny.trace = TRUE.

SEND {"busy":"busy"}

SEND {"custom":{"shinyjs-myfunction":{"data":["test1","test2"]}}}

SEND {"busy":"idle"}

So after clicking the button, the Javascript function seems to be executing, but no output/download appears.

Community
  • 1
  • 1
dkreeft
  • 494
  • 3
  • 15

1 Answers1

0

So indeed the issue was in the last 4 lines of code link. I have replaced the four lines with similar code. But added a required line for use in FF:

var encodedUri = encodeURI(csv);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

Based on How to export JavaScript array info to csv (on client side)?

I only have to find a way to correctly pass the data from R to the Javascript function.

edit: I have found how to do that here!

dkreeft
  • 494
  • 3
  • 15