<html>
<p> Some html </p>
<script> some script </script>
</html>
如何识别脚本标签并将其呈现为内容。
我有一个专门用于在网页中显示 html 的 div,如果它有任何脚本,我想将它们呈现为内容,但是在将 html 附加到 div 时,脚本会被执行,这是我不希望发生的情况。如何阻止脚本执行,是否有任何库可以做到这一点。
注意: 1. 内联脚本也应该被阻止执行。 2. 附加的 Html 内容是动态的,从电子邮件监听器源获取
提前致谢!
最佳答案
but while appending the html to the div, the script gets executed which I dont want to happen. How to keep the script from executing, are there any libraries to do that.
既然你说你已经有了div内容,一旦你追加它,脚本就会被执行,这是默认行为,我们能做的是在追加你的div内容之前,我们可以修改内容字符串来替换<script>
和</script>
通过<script>
和</script>
。这是它的演示。
var divContent = '<script>alert("I must not execute!!");<\/script>';
var res = divContent.replace(/<script/g,"<script>").replace(/<\/script/g,"</script>");
document.getElementById("output").innerHTML = res;
<div id="output">
</div>
关于javascript - 将脚本渲染为 HTML 而不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083598/