-
-
Save cferdinandi/6558de220add70f851aed1721c9665b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>encodeHTML()</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script> | |
/** | |
* Encode the HTML in a user-submitted string | |
* https://portswigger.net/web-security/cross-site-scripting/preventing | |
* @param {String} str The user-submitted string | |
* @return {String} str The sanitized string | |
*/ | |
function encodeHTML (str) { | |
return str.replace(/data:/gi, '').replace(/javascript:/gi, '').replace(/[^\w-_. ]/gi, function (c) { | |
return `&#${c.charCodeAt(0)};`; | |
}); | |
} | |
let app = document.querySelector('#app'); | |
// app.innerHTML = '<img src="x" onerror="alert(1)">'; | |
app.innerHTML = encodeHTML('<img src="x" onerror="alert(1)">'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment