Skip to content Skip to sidebar Skip to footer

Avoid Javascript Injection While Maintaining Html?

$('#id').append(dataHtml); when injected with an alert box appears on the screen showing test.I encoded the html but then it appeared as

Solution 1:

you could just use a simple regular expression to remove all script tags:

dataHtml = dataHtml.replace(/<script.*>[\s\S]*.*[\s\S]*<\/script>/g,"");

some explanation:

  • .* : all characters except linebreaks (* times)
  • [\s\S]* : linebreaks

to test if everything matches as expected you can use an online tool with an example of your dataHtml value (http://www.regexr.com/ for example).

Solution 2:

Append the script element with the type attribute set to something other than text/javascript, i.e. like this:

<scripttype="text/template">alert('test');</script>

This script tag will not be parsed or run as javascript.

Post a Comment for "Avoid Javascript Injection While Maintaining Html?"