简体   繁体   中英

Injecting Javascript snippet in HTML

I have a textbox where user can input html snippet

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)

VIEW

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

Where html.Script is an html helper

My problem is it gets deformed in the Client 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.

It doesn't look like KendoUI has a built in method to unescape HTML, but it's easy enough to do:

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?

Try with this javascript filter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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