Use project Javascript and CSS files in a Google A

2019-01-17 16:41发布

If I create a simple HTML web app in Google Apps Script, like this:

function doGet() {
    return HtmlService.createHtmlOutputFromFile("index.html");
}

and index.html looks like this:

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<div>Test</div>

is it possible to add JS and CSS files as part of the project and include them using script and link tags, or do they have to be inline/hosted elsewhere?

4条回答
趁早两清
2楼-- · 2019-01-17 17:12

You can directly render a file inside a scriptlet tag.

<?!= HtmlService.createTemplateFromFile("example.js").getRawContent() ?>

Create the example.js.html file in your apps script project. While rendering in the scriptlet tag do not mention the extension ".html"

查看更多
Melony?
3楼-- · 2019-01-17 17:26

For now, it is not doable to have your CSS and JS script to be part of your Google Apps Script project. You will have to host it somewhere else and point the URL in your template.

查看更多
时光不老,我们不散
4楼-- · 2019-01-17 17:26

Here is a workaround I have found useful:

  1. Add this function to your server-side Javascript:

    function getContent(filename) {
        return HtmlService.createTemplateFromFile(filename).getRawContent();
    }
    
  2. Add a second 'html' file to your project that contains only the JS or CSS surrounded by <script> or <style> tags as appropriate.

    <!-- myscript.js.html -->
    <script>
        alert("Script included!");
    </script>
    
  3. Now you can include the script in your main HTML template like this:

    <?!= getContent("myscript.js") ?>
    

This way, you can have your JS and CSS split into as many files as you like and keep them all accessible from within the Apps Script project.

查看更多
Melony?
5楼-- · 2019-01-17 17:32

Google provides a similar solution here.

Basically, they suggest you add this function to your .gs file:

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .getContent();
}

and add one or both of these to your .html file:

<?!= include('Stylesheet'); ?>
<?!= include('JavaScript'); ?>

the names in quotes of course referring to separate .html files containing your JS or CSS code with <script> or <style> tags.

查看更多
登录 后发表回答