简体   繁体   English

解析包含脚本标签和document.write的HTML字符串

[英]Parse HTML string containing script tag and document.write

I have below string. 我有下面的字符串。 It has nested document.write string statements. 它具有嵌套的document.write字符串语句。 I want to add text contents of innermost script to document. 我想将最里面的脚本的文本内容添加到文档中。

"document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')"

How can I parse this string so that Hello World gets added in document. 如何解析此字符串,以便将Hello World添加到文档中。 For eg html output can be as below.(can be in body or div, anything is ok.) 例如,html输出可以如下。(可以在body或div中,一切正常。)

<body>Hello World</body>

PS there can be any number of nested document.write statements. PS可以有任意数量的嵌套document.write语句。 Need to parse this string which can handle n level of nesting. 需要解析该字符串,它可以处理n级嵌套。

Well I figured it out now. 好吧,我现在想通了。

    var str = "document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')";
    var aStr, scriptEle = document.createElement('script');
    aStr = str.replace(/["']/g, '"');
    aStr = aStr.replace(/"<script>document.write/g, "");
    aStr = aStr.replace(/;<\/script\>"/g, "");
    scriptEle.innerHTML = aStr;
    // console.log(aStr);
    document.body.appendChild(scriptEle);

This also handles n level of nesting. 这也可以处理n级嵌套。

You will basically have to tell the script to execute the script inside the <script> tags. 您基本上必须告诉脚本执行<script>标记内的<script> You can achieve this by doing this 您可以通过执行此操作

var code = "<script>document.write(\"Hello World\");</scr"+"ipt>";
$('body').append($(code)[0]);

Which will happily display hello world in the body tags. 它将愉快地在body标签中显示hello world。 You can use this approach to get your script executed by appending it on any tag. 通过将脚本附加到任何标签上,可以使用此方法来执行脚本。 Here is the jsfiddle and an SO answer that can give you an idea as to how to be able to execute a js which gets appended dynamically 这是jsfiddle和一个SO答案 ,它可以使您了解如何执行动态附加的js。

Hope that helps :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM