How to sanitize innerHTML?

I’m building a floating div to be displayed in the target website. I copy the structure from a constant read-only property and replace fields such as {%name} with relevant data. While this is absolutely safe, since I don’t use user input, it generated a warning while submitting the extension.

You can’t use any API that allows you to build HTML from a string. Reviewers will complain about it and you will have to refactor it.

What you can do, is create “div” using document.createElement('div') and then use textContent property to change the text inside:

Then use appendChild to put it to DOM. Again, you can’t use append nor prepend for the same reason.

If you have a lot of DOM operation, consider using some UI library like Angular, Vue or React.

How using prepend is considered unsafe?

I’m looking at DOMPurify, it is a HTML sanitizer, however it is not liking my URI starting with moz-extension: would implementing a sanitizer be accepted?

Prepend allows passing a string containing HTML.
But you can use insertAdjacentElement as a safe alternative.

I don’t know if sanitizer would help, especially if you would write it yourself. I would avoid forbidden API if possible (and in many cases, it is possible).

I realized this is a duplicate suggestion from another thread.

This sounds like what HTML Templates are for. I don’t have a nicely coded example, but you could take a look at this thing I hacked together some time back:


JS to clone, populate, and insert the element:

It builds these rows:

Could not find that in docs, did you use them?

Templates are part of the Web API, not the WebExtensions API:


This can work for option page I think, how do you inject a template in the content script? Not mechanically, i know how you can inject HTML but rether mean why would you inject a template in the user page?

Why not?

(Additional text to let me post my answer, since it has to be 20 characters)

I don’t like the idea to have fluff in the user interface (brwoser) if there is a way to load the template from a file that would be great for me.