Is it 100% safe to do the following?:
var untrusted_input_from_3rd_party = '<script>alert("xss")<\/script>';
document.getElementsByTagName('body')[0].appendChild(document.createTextNode(untrusted_input_from_3rd_party));
Considering that the third party can input anything (HTML, CSS, etc.), can I be sure it won't do any harm if I pass it through createTextNode
and then add it to the dom?
This is a fine way to prevent XSS. DOM manipulation via createTextNode
is widely used to safely embed third party text.
That said, there are problems besides XSS. It doesn't do anything to stop social engineering attempts if the untrusted input is something like:
ALERT: We have detected malware on your computer. Copy and paste http://evil.org/ into your browser URL bar to fix the problem.
The best way to prevent social engineering (besides not including third-party content) is to make it clear that the content comes from a third party.
Tested it now. Seems to be correct. If something goes wrong - it should be browser bug, not yours.
As usual server should make a correct html view of all user inputs and then give it back to user.
But to lower server loading (and if it's acceptable) you can use this for sure.
I dont see this being executed in any standard modern browsers as its being rendered as a text node. Good read: http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_three.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With