Employee
Employee

Reputation: 2401

Send a variable from HtmlService to a Google Apps Script function

I have a Google Apps Script function called showModalReport() to which I pass an object called reportData, which is of the type Javascript object (it has property and value pairs). This function creates and serves an HtmlTemplate:

function showModalReport(reportData) {

  var template = HtmlService.createTemplateFromFile('modalReport');

  template.reportData = reportData; // this makes reportData available in the HTML modal dialogue

  template = template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);

  SpreadsheetApp.getUi().showModalDialog(template, 'Test Report');

}

Then here's my modalReport.html file:

<!DOCTYPE html>

Report Name: <?= reportData.name ?>

<input type="button" value="Email Report" onclick="onClickFunctions(???)" />

<script>

function onClickFunctions(reportData) {

  google.script.run.withSuccessHandler( function() { google.script.host.close(); }).emailReport(reportData);

}

</script>

The dialogue works and correctly displays the report name, so I know that the reportData variable is available. Next I want it so that when the user clicks the button, it calls the emailReport() function, which emails the report data to someone then closes the modal dialogue.

Here is emailReport():

function emailReport(reportData) {

  Logger.log('reportData: ' + reportData);

  // the email code

}

But the emailReport() function needs to have the reportData object passed as an argument, and this is the part I'm stuck on. How do I pass reportData to emailReport()?

I tried these already:

onclick="onClickFunctions(reportData)" // the Javascript console outputs the error: "Uncaught ReferenceError: reportData is not defined"

onclick="onClickFunctions(<? reportData ?>)" // reportData gets sent in to the function but is null 

onclick="onClickFunctions(this.reportData)" // reportData gets sent in to the function but is null

Any idea how I can send that variable to the function?

Also, I am aware that there are many other questions here that are similar to mine. I read and tried code from many of them, as well as trying what was recommended in Google's HTMLService documentation, but I'm still stuck.

Upvotes: 0

Views: 1679

Answers (1)

Cameron Roberts
Cameron Roberts

Reputation: 7367

You could JSON.stringify reportData and pass that around:

template.reportData = reportData;
template.reportDataJSON = JSON.stringify(reportData);

then:

onclick="onClickFunctions('<?= reportDataJSON ?>');

and:

function emailReport(reportData) {
    var reportData = JSON.parse(reportData);
}

Upvotes: 2

Related Questions