5 ms·
(For security purposes, in vanilla js we should all be using textContent, not innerHTML, and creating dom nodes directly.)
by roguecoder 7y ago
(For security purposes, in vanilla js we should all be using textContent, not innerHTML, and creating dom nodes directly.)
- kccqzy 7y agoWhen you control the data, innerHTML is fine. It's only untrusted data coming from the user that's the problem.
- nitrogen 7y agoinnerHTML has to parse the html, so won't it be a bit slower?
- kccqzy 7y agoWouldn't the JavaScript engine need to parse your long and complicated chains of `document.createTextNode(blah)` or `parent.appendChild(foo)`?
- roguecoder 7y agoOnly 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.
- algesten 7y agoapart from where you actually have html formatted text. not plain text.
- kccqzy 7y agoYou 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.
- MaulingMonkey 7y agoIn 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!