Using setHTML() Against Malicious HTML Injection

The easiest way to add HTML content to an element is by using innerHTML. This attribute allowed for easily setting HTML or text directly into an HTML element without much code. The other way included several steps to take to form a proper element using document.createElement and using document.createTextNode for the content of this element. It was very tedious but with InnerHTML, it was just setting a string to an element to inject HTML. Example:

let myString = "<span>Hello World</span>";
document.getElementById('example').innerHTML = myString;

This property was useful but very dangerous because it can inject malicious code into the page. However, there is a method added to an HTML element in the DOM that comes to fix this problem: setHTML(). It arrives at a good time when there is some controversy about the security of htmx by injecting malicious code if not used properly. Something that is unfair and uninformed because you should always validate your data on the server. We all must know that you should never trust the data that comes from the client.

Using the setHTML() Method

Using the previous example, it is necessary to create a sanitizer object that must be passed with the string to the setHTML method.

const saObj = new Sanitizer();
let myString = "<span>Hello World</span>";
document.getElementById('example').setHTML(myString, { sanitizer: saObj });

This will have the same results without the fear of injecting malicious code into your page.

My only complaint is that this approach is tedious considering that you need to create a Sanitizer object. The sanitizer object should have been included by default and we just needed to use the unsanatized string to pass to the .setHTML method to do its magic. Also, at the time of this writing, not all major browsers are supporting it. Therefore, it might take a little while before it is implemented in all browsers.

Teylor Feliz
Teylor Feliz

Teylor is a seasoned generalist that enjoys learning new things. He has over 20 years of experience wearing different hats that include software engineer, UX designer, full-stack developer, web designer, data analyst, database administrator, and others. He is the founder of Haketi, a small firm that provides services in design, development, and consulting.

Over the last ten years, he has taught hundreds of students at an undergraduate and graduate levels. He loves teaching and mentoring new designers and developers to navigate the rapid changing field of UX design and engineering.

Articles: 182