You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向Google Web应用URL添加查询字符串时出现HTML格式错误

Google Apps Script中createTemplate函数URL拼接导致HTML格式错误的问题

我在Google Apps Script里编写了createTemplate函数,想要给Google Web应用的URL添加查询字符串,目标URL是https://script.google.com/a/macros/xxxxx.xxx.xx/s/beenchangedforsecurity/exec?p=987654321。但运行代码时抛出异常:Exception: Malformed HTML content: https://script.google.com/a/macros/xxxxx.xxx.xx/s/beenchangedforsecurity/exec?p=000002036。

相关代码如下:

//htmlFileName: String
function createTemplate(htmlFileName) {
    let {protocol,stdName} = getProtocolData()
    let params = protocol   // protocol: String, exemple 987654321
    let url = 'https://script.google.com/a/macros/xxxxx.xxx.xx/s/beenchangedforsecurity/exec'

    url += '?' + 'p' + '=' + params

  /** **MY GOAL: url**   *
  * https://script.google.com/a/macros/xxxxx.xxx.xx/s/beenchangedforsecurity/exec?p=987654321
  */

 let html = HtmlService.createTemplateFromFile(htmlFileName)  
 html.protocol = protocol
 html.stdName  = stdName
 html.url      = url
 Logger.log(html.protocol)
 Logger.log(html.stdName)
 Logger.log(html.url)

 return html.evaluate().getBlob().getDataAsString() }

问题原因

错误核心是URL插入HTML模板时未正确处理,导致HTML解析引擎判定内容格式非法。直接拼接URL参数还存在隐性风险:如果protocol包含特殊字符(如&、空格等),会破坏URL结构,进一步加剧HTML格式错误概率。

解决方案

  1. 对URL参数进行编码:用encodeURIComponent()处理参数值,避免特殊字符干扰解析。
  2. 规范模板中URL的渲染方式:在HTML模板文件中,使用自动转义的输出语法<?= url ?>来插入URL,避免原始字符触发HTML格式错误。

修改后的代码:

//htmlFileName: String
function createTemplate(htmlFileName) {
    let {protocol, stdName} = getProtocolData()
    // 对参数值做URL编码处理
    let encodedProtocol = encodeURIComponent(protocol)
    let url = 'https://script.google.com/a/macros/xxxxx.xxx.xx/s/beenchangedforsecurity/exec'

    url += '?p=' + encodedProtocol

    let html = HtmlService.createTemplateFromFile(htmlFileName)  
    html.protocol = protocol
    html.stdName = stdName
    html.url = url

    Logger.log(html.protocol)
    Logger.log(html.stdName)
    Logger.log(html.url)

    // 直接返回HtmlOutput对象即可,无需转成字符串;若必须转字符串,确保模板无语法错误后用getContent()
    return html.evaluate()
    // return html.evaluate().getContent()
}

额外检查项

  • 确认HTML模板文件无语法错误(如未闭合标签、非法属性值等)。
  • 模板中输出URL时,必须使用<?= url ?>(自动转义HTML字符),而非<?!= url ?>(输出原始内容,易引发格式错误或注入风险)。

内容的提问来源于stack exchange,提问作者jcom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:35:48