Reputation: 35
I have been reading about xss and some questions have raised, but most of all I was wondering if there is a way to avoid it in the frontend?
Let's say my backend logic is not working properly and I have entered a field with value:
"name": "<script> alert('hello') </script>"
If we use the html tag <p>
to display the information it executes the javascript.
I have searched it and found the tag <xmp>
but it is marked as "Obsolete", but I didn't find any other way that is not obsolete to not execute the javascript. So is there any way to protect the end-user in the front end from executing malicious scripts even if we somehow allow the script to be injected in the database?
Upvotes: 1
Views: 1392
Reputation: 370629
Although it would certainly be better to secure the database from unsafe input, one option is to simply assign to an element's textContent
rather than its innerHTML
, to ensure that the string from the database gets parsed as text, rather than as HTML markup:
const databaseText = "test input 1<span>test input 2</span><script> alert('EVIL SCRIPT')</scr" + "ipt><span>test input 3</span>";
const p = document.body.appendChild(document.createElement('p'));
p.textContent = databaseText;
If the string is expected to contain HTML markup in addition to possibly unsafe script
tags, one might think that you could use something like DOMParser to strip out all script
tags before inserting the HTML markup into the actual document, but that wouldn't be enough protection, due to possible inline handlers like <.. onclick="...">
. Thanks to @GaborLengyel for pointing that out.
Upvotes: 1