Re:If Web Components are so great, why am I not using them?
by resonious on Thursday August 03, 2023 @05:42AM
(#36983524)
You get sanitization for free by using built in browser methods like setAttribute and textContent=.
[ Parent
| on HN ]
Re:If Web Components are so great, why am I not using them?
by jongjong on Thursday August 03, 2023 @06:25AM
(#36983830)
Agreed, this is the safe approach if you create elements using document.createElement().
For cases where you want to generate some HTML as strings to embed within your component's template string (e.g. in a React-like manner using Array.prototype.map), you would have to escape the variables provided by the back end in case they contain HTML tags which could be used as an XSS attack.
Although such sanitization function is trivial to implement... In my previous comment, I mentioned using document.createElement() as a fallback if in doubt. It's safe to create the elements with the DOM API and using the textContent property as you suggest. That's why I don't see sanitization as a strong excuse to avoid using plain Web Components.