Dont Use innerHTML
"innerHTML" is a useful function in certain situations, but if misused, it can allow others to infiltrate your web app. In this article, I'll explain why this is a concern and suggest an alternative approach.
First, let us look at why this can be bad, here is a sample code. In this code we have a simple input and a button. If we click the button it will display the output on our div output.
HTML CODE:
<input id="our-input-field" type="text" />
<button onclick="clickFunction()">Go</button>
<div id="output-div"></div>
JS CODE:
function clickFunction() {
console.log('asdfasdf')
let val = document.getElementById('our-input-field').value;
document.getElementById('output-div').innerHTML = val;
}
This works fine, its good. But if no additional code to check the value this might cause a problem. here is a simple code if its just a simple text.
But what if we add something that can run a script like this: <img src="" onerror="alert('asdfa')" />
. Running This will run alert something because it cant find the img source so it triggered the onerror property.
So what is the ALTERNATIVE?
The alternative is using the setHtml
function.
function clickFunction() {
console.log('asdfasdf')
let val = document.getElementById('our-input-field').value;
// document.getElementById('output-div').innerHTML = val;
// alternative
document.getElementById('output-div').setHTML(val);
}
The "setHTML()" method of the Element interface is used to safely insert a sanitized string of HTML into the DOM as a subtree of the element. It's a secure alternative to using "Element.innerHTML" when inserting untrusted HTML strings into an element.
The only downside with this one, is that its still in its experimental state and not yet supported on other browsers, but this function will be available once function experimental is done. Browser Compatibility: