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.