I came up with this solution.
Suppose we want to add some html to an element with insecure data from a user or database.
var unsafe = 'some unsafe data like <script>alert("oops");</script> here'; var html = ''; html += '<div>'; html += '<p>' + unsafe + '</p>'; html += '</div>'; element.html(html);
This is unsafe for XSS attacks. Now add this.
$(document.createElement('div')).html(unsafe).text();
So this is
var unsafe = 'some unsafe data like <script>alert("oops");</script> here'; var html = ''; html += '<div>'; html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>'; html += '</div>'; element.html(html);
This is much easier for me than using .replace() , and it will delete !!! all possible html tags (hopefully).
Kostiantyn Mar 30 '16 at 9:53 on 2016-03-30 09:53
source share