为什么< / script>正在验证js字符串中的标记 [英] why </script> tag in js string is being validated

查看:60
本文介绍了为什么< / script>正在验证js字符串中的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下页面

<html>
<head>
    <script type="text/javascript" src="e01.js"></script>
</head>
<body>
<script type="text/javascript">
var obj={someHTML: "<script>alert('a');</script>rest of the html",  
               someOtherAttribute:"some value"};
    alert(obj.someHTML);
</script>
</body>
</html>

在我对象的someHTML属性中我有< / script> 字符串中的标记。但是浏览器将其读作实际的关闭标记并关闭脚本元素。这里有什么我想念的吗? (在ff和chrome中尝试过)

in someHTML attribute of my object I have </script> tag in a string. but browser reads this as actual close tag and closes the script element. is there anything I am missing here? (tried it in ff and chrome)

推荐答案

HTML在之前解析并独立于Javascript。当前的浏览器行为是,一旦找到打开的标签< script> ,浏览器将切换到脚本数据状态并将所有后续数据解释为脚本,直到找到< / script>

HTML is parsed before and independent from Javascript. The current browser behavior is that, once an open tag <script> is found, the browser will switch to "Script Data State" and interpret all following data as script until a </script> is found.

< / script> <检测到/ code>无关紧要 - 在JS字符串,JS注释,CDATA部分甚至HTML注释中。

Where the </script> is detected doesn't matter — inside a JS string, a JS comment, a CDATA section, or even HTML comment.

你需要制作字符串看起来不像< / script> 到HTML解析器。最简单的方法是写<$ h $ => https://stackoverflow.com/questions/3509818/why-script-tag -in-js-string-is-being-validated / 3509843#3509843> @ Daniel 的回答。

You need to make the string does not look like </script> to the HTML parser. The simplest way is to write <\/script> as in @Daniel's answer.

这篇关于为什么&lt; / script&gt;正在验证js字符串中的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆