简体   繁体   English

在 HTML 中注入 Javascript 片段

[英]Injecting Javascript snippet in HTML

I have a textbox where user can input html snippet我有一个文本框,用户可以在其中输入 html 片段

example: user input this in the field示例:用户在字段中输入

// <![CDATA[
    <tr>
        <td>
            #= Position #
        </td>
        <td>
            #= Description #
        </td>
        <td>
            #= Location #
        </td>
        <td>
            <a href="@Url.Action("Delete")/#= Id #" class="delete-link">Delete</a>
        </td>
    </tr>
// ]]>

I save it to database and call it by demand in the client ui as KTemplatePart.Script (KendoUI Template)我将它保存到数据库并在客户端 ui 中按需调用它作为 KTemplatePart.Script(KendoUI 模板)

VIEW看法

@Html.Script(
    @<script id="jobTemplate" type="text/javascript">
       @Model.KTemplatePart.Script
     </script>
)

Where html.Script is an html helper其中 html.Script 是一个 html helper

My problem is it gets deformed in the Client ui我的问题是它在客户端 ui 中变形

<script id="jobTemplate" type="text/javascript" >

    &lt;![CDATA[

        &lt;tr&gt;
            &lt;td&gt;
                #= Position #
            &lt;/td&gt;
            &lt;td&gt;
                #= Description #
            &lt;/td&gt;
            &lt;td&gt;
                #= Location #
            &lt;/td&gt;
            &lt;td&gt;
                &lt;a href=&quot;@Url.Action(&quot;Delete&quot;)/#= Id #&quot; class=&quot;delete-link&quot;&gt;Delete&lt;/a&gt;
            &lt;/td&gt;
        &lt;/tr&gt;

    // ]]&gt;

         </script>

Is there a workaround on this?有解决方法吗?

This is by design for security reasons, to prevent script injection, attacks.这是出于安全原因设计的,以防止脚本注入和攻击。

Allowing HTML to be inserted into the DOM leaves your application vulnerable, and thus by default, the input is escaped.允许将 HTML 插入 DOM 会使您的应用程序易受攻击,因此默认情况下,输入被转义。

It doesn't look like KendoUI has a built in method to unescape HTML, but it's easy enough to do:看起来 KendoUI 没有内置的方法来取消转义 HTML,但它很容易做到:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

from: Unescape HTML entities in Javascript?来自: 在 Javascript 中 Unescape HTML 实体?

Try with this javascript filter.试试这个 javascript 过滤器。

function filter(value) {
  const removeTag = new RegExp("(<[a-zA-Z0-9]+>)|(</[a-zA-Z0-9]+>)", "g");
  return value.replace(removeTag, "");
}

You can see the result on codepen.你可以在codepen上看到结果。

Codepen代码笔

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

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