Last active
July 8, 2023 23:24
-
-
Save dfkaye/8687c93207c9f5cb5e82204a7d2df82a to your computer and use it in GitHub Desktop.
using Element.setHTML to get around the Trusted HTML CSP restriction
This file contains hidden or 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
// 7 July 2023 | |
// using setHTML to get around the Trusted HTML CSP restricted apps. | |
// Our HTML fragment text | |
var source = ` | |
<section id="x-fragment"> | |
<fake>&& < < title</fake> | |
<meta charset="UTF-8"> | |
<script>alert(1);</script> | |
</section> | |
`; | |
try { | |
// The following fails in Trusted HTML CSP restricted apps like Chrome's blank tab. | |
var div = document.createElement("DIV"); | |
div.innerHTML = source; | |
} catch (e) { | |
console.error(e); | |
/* | |
This document requires 'TrustedHTML' assignment. | |
------- | |
TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment. | |
*/ | |
} | |
// However we can use the following brain-dead polyfill to assign an HTML | |
// string to an element's innerHTML... | |
(function setHTML(unset) { | |
if (unset) { | |
return delete Element.prototype.setHTML | |
} | |
typeof Element.prototype.setHTML == 'function' || ( | |
Element.prototype.setHTML = function setHTML(innerHTML) { | |
this.innerHTML = innerHTML; | |
} | |
); | |
}).call(0, 0); | |
/* test it out */ | |
var div = document.createElement("div"); | |
div.setHTML(source); | |
document.body.appendChild(div); | |
console.log(div.innerHTML); | |
// Some surprising differences as of 8 July 2023! | |
// firefox removes unknown tags, the meta tag, and the script tag | |
/* | |
<section id="x-fragment"> | |
&& < < title | |
</section> | |
*/ | |
// chrome removes unknown elements and their content, and the script tag | |
/* | |
<section id="x-fragment"> | |
<meta charset="UTF-8"> | |
</section> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment