Is createTextNode completely safe from HTML inject

2019-02-21 13:29发布

问题:

I'm working on a single page webapp. I'm doing the rendering by directly creating DOM nodes. In particular, all user-supplied data is added to the page by creating text nodes with document.createTextNode("user data").

Does this approach avoid any possibility of HTML injection, cross site scripting (XSS), and all the other evil things users could do?

回答1:

It creates a plain text node, so yes, as far as it goes.

It is possible to create an XSS problem by using an unsafe method to get the data from whatever channel it is being input into to createTextNode though.

e.g. The following would be unsafe:

document.createTextNode('<?php echo $_GET['xss']; ?>');

… but the danger is from the PHP echo, not the JavaScript createTextNode.