Javascript 文字包含脚本标签时出现“未终止的模板文字”语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36607932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:16:59  来源:igfitidea点击:

"Unterminated template literal" syntax error when literal contains script tag

javascripthtmlecmascript-6script-tagtemplate-literals

提问by Michael

I'm using ES6 template literals to construct some HTML in strings, and so far it has been working fine. However, as soon as I try to put the literal text </script>in my string the browser throws up and throws the syntax error:

我正在使用 ES6 模板文字在字符串中构造一些 HTML,到目前为止它一直工作正常。但是,一旦我尝试将文字文本</script>放入我的字符串中,浏览器就会抛出并抛出语法错误:

SyntaxError: Unterminated template literal

Here is a simple JavaScript sample which throws the error:

这是一个抛出错误的简单 JavaScript 示例:

var str=`
<script>
</script>
`
var pre = document.createElement('pre')
pre.textContent = str
document.body.appendChild(pre)

See the above code in JS Fiddle.

请参阅JS Fiddle 中的上述代码。

It appears that what is happening is that it gives up looking for the end literal quote and instead starts treating everything at point as literal HTML, so all the JavaScript after that point is incorrectly treated as HTML, which it is not!

看起来正在发生的事情是它放弃了寻找结尾文字引用,而是开始将所有内容视为文字 HTML,因此该点之后的所有 JavaScript 都被错误地视为 HTML,事实并非如此!

If I replace scriptby anyother legal HTML tag (and even invalid tags like scripty) then it works just fine, so I can't see how this can possibly be a syntax error or a weird case where I think I have typed one character (e.g. the backtick) but instead have typed another that looks almost like it.

如果我替换script任何其他合法的 HTML 标记(甚至是无效的标记scripty,例如反引号),而是输入了另一个看起来很像的。

I am literally creating a string (to my understand, at compile time), the browser should notbe attempting to treat it as HTML or in any way parse it. So what gives?

我实际上是在创建一个字符串(据我所知,在编译时),浏览器应该尝试将其视为 HTML 或以任何方式解析它。那么什么给呢?

回答by Micha? Per?akowski

If you insert </script>inside a script tag, no matter if it's a string in quotes, apostrophes, or even a template literal, it will alwaysclose the script tag. You have to escape it, for example like that:

如果你插入</script>一个脚本标签中,无论是在引号,顿号,甚至是模板文字,它将一个字符串始终关闭脚本标签。你必须逃避它,例如像这样:

var str=`
<script>
<\/script>
`
var pre = document.createElement('pre')
pre.textContent = str
document.body.appendChild(pre)

However, if you use external script <script src="url"></script>, it should work fine without escaping.

但是,如果您使用 external script <script src="url"></script>,它应该可以正常工作而不会转义。