Skip to content

Instantly share code, notes, and snippets.

@tracker1
Last active July 31, 2020 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tracker1/3eecffc687d8a07ab2dec60603304415 to your computer and use it in GitHub Desktop.
Save tracker1/3eecffc687d8a07ab2dec60603304415 to your computer and use it in GitHub Desktop.
function sanitizeHtml(input) {
if (typeof input !== 'string') return input;
if (input.indexOf('<') === -1) return input;
const div = document.createElement('div');
div.innerHTML = input;
div.querySelectorAll('script').forEach((el) => el.remove());
div.querySelectorAll('style').forEach((el) => el.remove());
div.querySelectorAll('*').forEach((el) => {
const events = el.getAttributeNames().filter((a) => a.indexOf('on') === 0);
events.forEach((e) => el.removeAttribute(e));
});
return div.innerHTML;
}
import cheerio from 'cheerio';
export default (input) => {
if (typeof input !== 'string') return input;
if (input.indexOf('<') === -1) return input;
const $ = cheerio.load(input || '');
$('body script').remove();
$('body style').remove();
$('body *').map((i, x) => {
const el = $(x);
const events = Object.keys(el[0].attribs).filter((k) => k.indexOf('on') === 0);
events.forEach((e) => el.removeAttr(e));
return el;
});
return $('body').html();
};
var input = '<div>this is a test <script>alert(1)</script></div>';
var expected = '<div>this is a test </div>';
console.log('test1', sanitizeHtml(input) === expected);
var input = '<div>this is a test <style></style></div>';
var expected = '<div>this is a test </div>';
console.log('test2', sanitizeHtml(input) === expected);
var input = '<div onmouseover="alert(1)">this is a test <img src=x onclick="alert(1)" /> too</div>';
var expected = '<div>this is a test <img src="x"> too</div>';
console.log('test3', sanitizeHtml(input) === expected);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment