如果您确实需要注入包含script标签的添加 html 代码并且您是安全问题的奖励,我建议使用像 jQuery 这样的库来处理<script>稍后添加的执行标签的跨浏览器问题。
此外,您需要注意各种陷阱,例如:
Html 解析是在脚本解析之前完成的,因此无论</script>出现在哪里,这都会立即结束您的脚本。
这些示例对于您在 html 页面中将该代码作为内联脚本的情况很重要。
示例 1:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
// if you add </script> <b>this is visible as html</b> and everything below is not script anymore
}
</script>
示例 2:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</script>";//the same problem here everything behind the closing script tag is html and not script anymore
}
</script>
因此,如果您需要一些脚本来注入,您需要使</script>html 解析器无法检测到:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</sc"+"ript>";//that way the html parser does not detect the closing script tag
}
</script>
更好的解决方案是根本不使用内联脚本,不仅因为这个原因,还因为您应该始终保持 css、js 和 html 分开。