I know this type of question might have asked many times but I am sure that this one is different than all of them. I have a Input TextArea control on server side, I am trying to remove all inline script or html injection. I was able to get rid of Script tags by doing this-
$(document).ready(function () {
$('#btnHTML').click(function () {
var textarea = document.getElementById("txtar1");
var stringOfHtml = textarea.value;
var wrappedString = '<div>' + stringOfHtml + '</div>';
var noScript = wrappedString.replace(/script/g, "THISISNOTASCRIPTREALLY");
var html = $(noScript);
html.find('THISISNOTASCRIPTREALLY').remove();
var tmp = document.createElement("DIV");
tmp.id = "tmp";
tmp.innerHTML = html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script');
document.body.appendChild(tmp);
alert(html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script'));
});
<textarea id="txtar1" style="width:200px;height:100px"></textarea><br/>
<input type="button" id="btnHTML" value="Remove HTML" />
But my purpose is not solved, I am trying to restrict or remove all types of inline script injection. Few examples are-
<div>
<table border="2">
<tr>
<td><b>ABCD</b></td>
<td onclick="javascript:alert('Hello')">
EFGH</td>
</tr>
</table>
</div>
<div>
<table border="2">
<tr>
<td><b>Test</b></td>
<td alert('Hello')>
Success</td>
</tr>
</table>
</div>
<META HTTP-EQUIV="refresh" CONTENT="1;url=http://www.test.com">
<BR SIZE="&{alert('Injected')}">
<DIV STYLE="background-image: url(javascript:alert('Injected'))">
Any help or suggestions would be very very helpful.
Instead of using inline JavaScript <script> ... source ... </script>
, using external JavaScript files and importing them using <script src="...">
helps to mitigate the attacks and make your website safe.
The way to do this in the modern browsers is to set the 'Content-Security-Policy' (CSP) property, either via meta attribute or headers.
you can use this tutorial to get more knowlege regarding this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With