如何在我的Google Apps脚本/Google表格HTML中包含脚本? [英] How do I include scripts in my Google Apps Script/Google Sheets HTML?

查看:89
本文介绍了如何在我的Google Apps脚本/Google表格HTML中包含脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使我的基于Apps脚本的HTML包含任何脚本.

I cannot get my Apps Script-based HTML to include any scripts.

我的HtmlServicedoGet函数工作正常:

function doGet() {
return HtmlService.createHtmlOutputFromFile('myhtmlfilename');
}

无论我的HTML文件上是否有任何脚本标签,我似乎都能得到以下信息:

I seem to get the following whether or not I have any script tags on my HTML file:

错误

我尝试将所有JavaScript存储在带有标签的单独HTML文件中(称为JavaScript.html),然后使用强制打印脚本将它们重新包含到HTML中.

I have tried storing all of my JavaScript in a separate HTML file with tags (called JavaScript.html) and then including them back into my HTML using force print scriptlets.

我的HTML文件包含我的脚本标签:

My HTML file containing my script tags:

<script>
function transferItems(){
google.script.run.test();
}

</script>

我的功能是将脚本HTML包含为scriptlet,我也尝试将其作为'getRawContent'而不是'evaluate':

My function to include the script HTML as a scriptlet, which I have also tried as 'getRawContent' instead of 'evaluate':

function include(filename) {
return HtmlService.createTemplateFromFile(filename).evaluate().getContent();
}

我的脚本:

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

我在我的code.gs中的函数,称为test():

My function in my code.gs, called test():

function test() {
alert("This is a test."); 
}

我要在其上调用test()函数的主HTML页面中的按钮:

My button in my main HTML page through which I am trying to call the test() function:

<button onClick="transferItems()">Transfer</button>

无论我尝试什么,页面最终都会在浏览器中将那些scriptlet显示为文本.

No matter what I try my page ends up displaying those scriptlets as text in the browser.

显示的结果

我想念什么?

我阅读的所有答案和教程均来自2015ish或更早的版本. 我觉得我在关注Google的文档.

All of the answers and tutorials I have read are from 2015ish or earlier. I feel like I am following Google's documentation.

推荐答案

如果使用HTMLService进行评估时,HTML文件中包含<?...?>脚本,则需要使用createTemplateFromFile()它们将被视为纯文本. createOutputFromFile()无法用于评估脚本标签.

If you have the <?...?> scriptlets in your HTML file when you evaluate with the HTMLService you need to use createTemplateFromFile() otherwise they will be treated as plain text. The createOutputFromFile() won't work for evaluating the script tags.

function doGet() {
 return HtmlService.createTemplateFromFile('myhtmlfilename').evaluate();
}

编辑:您的include不需要评估那些<? ?>脚本.所以它只需要像这样:

Your include doesn't need to evaluate those <? ?> scriptlets. So it just needs the be like this:

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

使用我的手机接听,所以代码可能并不完美.

Using my phone to answer so the code might not be perfect.

这篇关于如何在我的Google Apps脚本/Google表格HTML中包含脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆