Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 18:06
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 cferdinandi/6558de220add70f851aed1721c9665b4 to your computer and use it in GitHub Desktop.
Save cferdinandi/6558de220add70f851aed1721c9665b4 to your computer and use it in GitHub Desktop.
<!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