Hacker News new | past | comments | ask | show | jobs | submit login

(For security purposes, in vanilla js we should all be using textContent, not innerHTML, and creating dom nodes directly.)



When you control the data, innerHTML is fine. It's only untrusted data coming from the user that's the problem.


Only if you can, with absolute certainty, keep track of which of those is which, and never have it change, or have some offline process polute data that was supposed to be clean.

There is almost never a reason to use innerHTML, and by avoiding it you reduce the surface that could be attacked.


You are just making things extreme without giving your fellow software engineers some confidence that they won't screw up. Plenty of variables are string constants, or numbers coerced into strings or some such. A good type system will always help though.


In the words of Jeff Atwood, "Give me parameterized SQL, or give me death" - and HTML escaping is little different. My fellow "software engineers" are human. They will screw up. That's simply a matter of human nature and statistics. Even if we only employ godlings, we'll eventually hire a human intern.

"It happens to be safe for the moment because it's a constant" isn't a high enough bar. I've refactored plenty of string constants to new locations, and then to dynamic strings. If that's the bar you're using, every such refactoring is now a security critical change that requires a thorough security audit.

There are uses of innerHTML, but the post you're replying to acknowledges that - "almost never". If you're building the APIs that enable safe DOM manipulation, you have some use cases. If you're serving HTML fragments directly from the server, you have some use cases - although I'd hope you're using safe APIs serverside if it's dynamic, instead of hand-building HTML in code!


apart from where you actually have html formatted text. not plain text.


innerHTML has to parse the html, so won't it be a bit slower?


Wouldn't the JavaScript engine need to parse your long and complicated chains of `document.createTextNode(blah)` or `parent.appendChild(foo)`?




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: