JSFiddle - React, Tailwind, and code Playground
by sys2061
HTML
<div id='results'>
</div>
JavaScript
// Implementation:
/**
* Encodes an HTML attribute using the browser's DOM methods
*/
function encodeAttr(text) {
const elem = document.createElement('p');
elem.setAttribute('title', text);
const elemHtml = elem.outerHTML; // <p title="encodedText"> or maybe <p title='encodedText'>
// Find out whether the browser used single or double quotes before encodedText
const quote = elemHtml[elemHtml.search(/['"]/)];
// Split up the generated HTML using the quote character; take item 1
return elemHtml.split(new RegExp(quote))[1];
}
// Demo:
const untrustedAttribute = '"><iframe src="javascript:alert(\'XSS\');">.jpg';
document.getElementById('results').innerHTML =
`<span title="${encodeAttr(untrustedAttribute)}"> My content </span>`;