UPDATE: Thank you everyone for your help, especially ale13. I have updated the question with the final code that worked for me.
I am trying to create a HTML button that pops up within my Google Sheets and on click it should trigger the download of the sheet. I created the button and everything else runs perfectly. When I manually get the link generated and click on it, the file downloads. However, when I click on the button, nothing happens.
This is the code to launch the HTML.
function downloadPopup(){
var html = HtmlService.createHtmlOutputFromFile('Button');
SpreadsheetApp.getUi().showModalDialog(html, 'Download Lists as CSV');
}
Setting and getting the property
PropertiesService.getScriptProperties().setProperty('urlD', downloadURL);
function urlHTML(){
return PropertiesService.getScriptProperties().getProperty('urlD');
}
This is the HTML
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<style>
.
.
.
</style>
</head>
<script>
var downloadURL = PropertiesService.getScriptProperties().getProperty('urlD');
function downloadFile(downloadURL){
window.open(downloadURL);
}
</script>
<body>
<div id="buttonlink"></div>
<button type="button" onclick="google.script.run.withSuccessHandler(downloadFile).urlHTML()" class="button">Download CSV</button>
</body>
</html>
Thanks a lot!
Advertisement
Answer
I suggest you modify the code as following:
Code.gs
function downloadPopup(){
var html = HtmlService.createHtmlOutputFromFile('Button');
SpreadsheetApp.getUi().showModalDialog(html, 'Download Lists as CSV');
}
function urlHTML(){
return downloadURL;
}
Button.html
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<style>
</style>
</head>
<script>
function downloadFile(downloadURL){
window.open(downloadURL, '_self');
}
</script>
<body>
<div id="buttonLink"></div>
<button type="button" onclick="google.script.run.withSuccessHandler(downloadFile).urlHTML()">Preview The Document</button>
</body>
</html>
Unless you really need two distinct functions for returning URL, I would suggest you to use just one which will return the URL directly when called. As a side note, it is important to bear in mind that Apps Script’s global variables are different in comparison to the ones in other programming languages – each new invocation of the functions will end up returning a new context to the script without memory of earlier executions unless these were kept. For storing a global variable correctly, I suggest you take a look at this class.
As for the HTML part, when the button is being clicked, the withSuccessHandler(downloadFile) allows you to specify a client-side callback function to run when the urlHTML() server function responds. In order to open the link in a new window, the window.open has been used.