Google App 脚本:模板文字中的 URL 导致“未捕获的语法错误:输入意外结束”

Mik*_*gan 1 google-apps-script

如果我onOpen()对 Google Docs 插件进行了此设置:

function onOpen(e) {
    DocumentApp.getUi().createAddonMenu()
        .addItem('Edit Template', 'showSidebar')
        .addToUi();
}

function showSidebar() {
    const html = HtmlService
        .createHtmlOutputFromFile("dist/addOn");
    html.setTitle("DocsNData Template Editor");
    DocumentApp.getUi().showSidebar(html);
}
Run Code Online (Sandbox Code Playgroud)

如果dist/addOn.html包含这个:

<html>
<head>
    <script>
        let x = `https://api.airtable.com`;
    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

当我尝试启动附加组件时,我在浏览器控制台中收到此错误:

userCodeAppPanel:3 Uncaught SyntaxError: Unexpected end of input

如果我更改字符串的内容,使其不再是 url,那么它就可以工作。换句话说:

<html>
<head>
    <script>
        let x = `abc`;
    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

所以问题不在于模板文字的使用。

此外,将 URL 作为普通字符串引用也是可行的,即这样就可以了:

<html>
<head>
    <script>
        let x = "https://api.airtable.com";
    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

所以字符串中的 URL 不是问题,模板文字也不是问题,模板文字中的 url 才是问题。我有两个问题:

  1. 为什么会出现这种情况?正确的纠正措施是什么?
  2. 错误消息中报告的行号与我的来源有何关系?

Tan*_*ike 6

  • Q1:为什么会出现这种情况?正确的纠正措施是什么?
  • 问题 2:错误消息中报告的行号与我的源有什么关系?

对于这些问题,这个答案怎么样?

A1:

我也经历过同样的情况。在这种情况下,我使用了以下解决方法。

从:

let x = `https://api.airtable.com`;
Run Code Online (Sandbox Code Playgroud)

到:

let x = `https:\/\/api.airtable.com`;
Run Code Online (Sandbox Code Playgroud)
  • let x = `https://api.airtable.com`;在 Google Apps 脚本端使用时,不会发生错误。所以我认为这可能是当前的规范或一个错误。
  • Google Issue Tracker:虽然我在 Google Issue Tracker 上搜索了这个问题,但没有找到。所以我向 Google Issue Tracker 报告了这个问题。https://issuetracker.google.com/issues/156139610

A2:

关于userCodeAppPanel:3,我认为首先需要确认错误信息。Uncaught SyntaxError: Unexpected end of input当看到错误消息时,这意味着语法不完整。据此,认为错误发生在脚本的末尾<script>...</script>。在这种情况下,3与 中的行的长度相同<script>...</script>

当看到以下脚本时,错误发生在let x = `https://api.airtable.com`;。但错误行是 脚本的结尾<script>...</script>。至此,3返回。

<html>
<head>
    <script>
        let x = `https://api.airtable.com`;
    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

在以下示例脚本的情况下,userCodeAppPanel:5 Uncaught SyntaxError: Unexpected end of input返回。因为 的行</script>位于第 5 行。

<html>
<head>
    <script>
        let x = `https://api.airtable.com`;


    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

作为另一个示例,当看到以下脚本时,

<html>
<head>
    <script>
    let x = "https://api.airtable.com";

    console.log(y);
    </script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)

出现错误,如Uncaught ReferenceError: y is not defined at userCodeAppPanel:4. 这样的话就可以清楚的找到错误线了。4的行也是如此console.log(y);

不幸的是,我在官方文档中找不到这方面的内容。