I recently started using Google Docs Spreadsheet and have started trying to script things in the sheet. In one particular sheet, I wanted to display a custom dialog box to the user and I've managed to do that.

Now, I want to make some table rows in the dialog clickable. I wrote some code that should do the job, but Caja seems to be removing the code that I wrote.

Simplified version of the code (that still has the problem):

function showSkillsForCurrentLevel() {
  var html, out, app;

    html = '<div>Text. Yay!</div>'
    + '<script>'
    + '(function(){'
    + '    "use strict";'
    + '    var toggleFinished = function toggleFinished(){'
    + '            this.classList.toggle("finished");'
    + '        },'
    + '        rows,'
    + '        i = 0;'
    + '    rows = document.getElementsByClassName("skill-leveling").getElementsByClassName("finishable");'
    + '    if (rows.length) {'
    + '        for (i = 0; i < rows.length; i += 1) {'
    + '            rows[i].onclick = toggleFinished;'
    + '        }'
    + '    }'
    + '}());'
    + '</script>';  
    out = HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.NATIVE).setTitle('Leveling Plan').setWidth(400).setHeight(400);
    app = SpreadsheetApp.getActiveSpreadsheet();
    app.show(out);
};

What I get in the displayed dialog is:

<caja-v-body>
    <div>Text. Yay!</div>
    <script></script>
</caja-v-body>

I assume that Caja is stripping the code for some reason but I cannot seem to find any documentation, or an example, anywhere of how to properly include scripts in Code.gs so that they remain intact post-Caja sanitization.

I assume others have run across this problem, and I'm hoping that someone will share a solution.

TLDR Version:

How do I include JavaScript in a dialog created by HtmlService.createHtmlOutput?

1

There are 1 best solutions below

2
On

My approach is to create the dialog like this :

  var htmlOutput = HtmlService.createHtmlOutputFromFile("customdialog.html").setTitle("your title").setWidth(350);
  htmlOutput.setSandboxMode(HtmlService.SandboxMode.NATIVE);
  DocumentApp.getUi().showDialog(htmlOutput)

The actual content of the dialog is in a separate HTML file called customdialog.html. Example implementation could be :

<html>
  <head>
    <script src="http://remoteserver/yourscript.js"></script>
    <script>... a local script</script>
  <body>
  <div>hello dialog</div>
  </body>
</html>

You can even include the javascript from a remote server, as the example demonstrates. I managed to include jquery and use jquery in the dialog with this approach.