</script>在 <script> 中的 JavaScript 字符串中标签 [英] </script> within a JavaScript string in a <script> tag
问题描述
我有一个应用程序,可以将各种内容生成到放置在页面上的 JavaScript 字符串中.我以为所有的转义都可以,但后来我遇到了一个奇怪的问题,我真的找不到原因:
I have an app that can generate all sorts of things into the JavaScript strings put on the page. I thought all the escaping were ok, but then I came across a weird problem that I couldn't really find a reason for:
这在 html 页面中不应该是合法的:
Shouldn't this be legal in an html page:
<script type="text/javascript">
alert("hello </script>");
</script>
'Legal' 意味着它会产生一个带有 hello </script>
的警报.
'Legal' meaning that it would produce an alert with hello </script>
.
显然,至少在我的机器上,moz 和 chrome 都会在警报字符串的 </script>
部分之后切断脚本,不产生警报并且输出混乱.有没有人遇到过这个,这是浏览器的错误吗?
Apparently both moz and chrome, on my box at least, cuts the scripting off after the </script>
part of the alert string, producing no alert and a messy output. Has anyone run into this, is this a browser bug?
推荐答案
HTML 解析为:
<script type="text/javascript">
alert("hello
</script>
");
</script>
第一次出现 时关闭打开的
元素.避免此问题的常用方法是在字符串中的
/
字符之前包含一个 \
:
With the first occurrence of </script>
closing the open <script>
element. The common way of avoiding this issue is by including a \
before the /
character in the string:
<script type="text/javascript">
alert("hello <\/script>");
</script>
这是有效的,因为 \
转义字符会阻止浏览器将 <\/script>
识别为结束标记.通常 \
在 JavaScript 字符串中用作转义序列,但由于没有 \/
序列,因此忽略转义字符并且字符串计算为 '</script'>
.
This works because the \
escape character will prevent the browser from recognizing <\/script>
as an end tag. Normally \
is used as an escape sequence in JavaScript strings, but as there's no \/
sequence, the escape character is ignored and the string evaluates as '</script'>
.
如果您遵循将所有 javascript 保存在外部 .js
文件中的良好做法,通常可以避免此问题.也就是说,通常会看到这种转义用于无响应 CDN 的本地脚本回退.
This issue can generally be avoided if you follow the good practice of keeping all of your javascript in external .js
files. That said, it's common to see this sort of escaping used for local script fallbacks for unresponsive CDNs.
这篇关于</script>在 <script> 中的 JavaScript 字符串中标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!