【问题标题】:Passing JS variable to HTML in Google Scripts在 Google Scripts 中将 JS 变量传递给 HTML
【发布时间】:2019-10-10 19:46:24
【问题描述】:

我正在尝试将通过电子邮件发送的 html 中的文本更改为我定义的 JS 变量。重要的是我在 Google Scripts 中执行此操作并拥有 2 个文件 Code.gs 和 Email.html。

似乎我的 html 无法访问 JS 变量,但我不确定我哪里出错了。我参考了一些类似的帖子,并尝试了一种不同的方法,但无法让它发挥作用。如果有人有建议,那就太好了。

代码.gs

var JSname;

function Email() {

  JSname = 'It works!'
  var theEmail = 'myemail@gmail.com';
  var theSubject = 'Email subject line';
  var template = HtmlService.createTemplateFromFile('Email');
  var message = template.evaluate().getContent();
  MailApp.sendEmail({ to: theEmail, subject: theSubject, htmlBody: message });
  return
}

电子邮件.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <span id="HTMLname">[Text here]</span>
    <script type="text/javascript" src="Code.gs">
      document.getElementById("HTMLname").innerHTML = JSname;
    </script>
  </body>
</html>

【问题讨论】:

  • 您在访问模板上设置的属性时遇到问题吗?如这里:developers.google.com/apps-script/reference/html/…
  • 没有与电子邮件 html 关联的 Javascript,即 htmlBody 参数。该 htmlBody 字符串中的所有内容都必须在字符串中定义。所以你可以假设你在body标签中。不要处理 DocType、html、head 或 script 标签。它们在电子邮件中都毫无意义。
  • 在发送电子邮件之前,您可以使用 Utilities.formatString() 服务器端替换您想要的任何变量。

标签: javascript html google-apps-script


【解决方案1】:

问题:

您正在使用超出范围的变量,就这么简单

修复:

使用模板变量:

code.gs

function doGet(e) {
  var template = HtmlService.createTemplateFromFile('Index'); // Or whatever you have
  var JSname = 'It works!' // Ideally var names should start with lowercase

  template.JSname = JSname // This is the IMPORTANT change

  // Build and return HTML in IFRAME sandbox mode. (Copied from GS directly)
  return template.evaluate()
    .setTitle('Web App Window Title')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function Email() {
  var theEmail = 'myemail@gmail.com';
  var theSubject = 'Email subject line';
  var template = HtmlService.createTemplateFromFile('Email');
  var message = template.evaluate().getContent();
  MailApp.sendEmail({
    to: theEmail,
    subject: theSubject,
    htmlBody: message
  });
}
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>
  <span id="HTMLname"><?= JSname ?></span>
</body>

</html>

来源:https://script.google.com/u/1/home/start

【讨论】:

  • 要修复的几个语法问题。 AppScript 具有较旧的 ECMA 解析器,因此不支持 let。而且你最后缺少一个匹配的花括号。
  • 谢谢麦克风,修复:)
  • 做了一些调整,效果很好。谢谢! @AP。
  • 很高兴它帮助了@JoeBo!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多