Skip to content

Instantly share code, notes, and snippets.

@koto
Created June 29, 2021 21:21
Show Gist options
  • Save koto/de7ec42a57c12259cbe4fa8fc19c1d78 to your computer and use it in GitHub Desktop.
Save koto/de7ec42a57c12259cbe4fa8fc19c1d78 to your computer and use it in GitHub Desktop.
(() => {
if (!('rawHTML' in HTMLElement.prototype)) {
const rules = {
createHTML: (ignore, tpl) => {
if (!Array.isArray(tpl) || !Array.isArray(tpl.raw) || tpl.raw.length != 1 /* it's all spoofable, but whatever */) {
throw new TypeError("Use el.rawHTML`<html here with no interpolation>`");
}
return tpl.join("");
}
};
let policy;
if (typeof trustedTypes !== "undefined") {
policy = trustedTypes.createPolicy('rawHTML', rules);
} else {
policy = rules;
}
HTMLElement.prototype.rawHTML = function(tpl) {
this.innerHTML = policy.createHTML('', tpl);
};
}
})();
@koto
Copy link
Author

koto commented Jun 29, 2021

This will install a function that allows for constant strings to be passed to element.rawHTML like so:

const el = document.querySelector('p');
el.rawHTML`i am a constant`;

el.rawHTML`anything ${"dynamic"} is not allowed`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment