Safe insertAdjacentHTML with user input? Or I should avoid it anyway?

It is possible to get extensions using innerHTML and alike approved without using DOMPurify. But you will always have the risk that (another) reviewer looks at it, and decides to disable your extension in AMO. I had an extension that used innerHTML and insertAdjacentHTML a lot. But suddenly a day I got the message it was disabled because of unsafe use of those methods. I went through the code and replaced most occurrences with something else(*). But in a few place where they were difficult to replace and I felt I could argue their use being safe, I wrote a comment in the code arguing for the use being safe. I got the extension re-enabled in AMO after this. BUT it is still my plan to get rid of most/all the remaining use of these methods, because I guess there’s still a risk another reviewer don’t like it.

(*)Generally I don’t feel like including the big “DOMPurify” library or similar into my extension. So I went the way of constructing the “DOM structures” manually instead. I created this little utility method which I personally find very handy for that:

function createRichElement(tagName, attributes, ...content) {
  let element = document.createElement(tagName);
  if (attributes) {
    for (const [attr, value] of Object.entries(attributes)) {
      element.setAttribute(attr, value);
    }
  }
  if (content && content.length) {
    element.append(...content);
  }
  return element;
}

With this you could create your example html (container) with:

let imgElem = createRichElement('img', {src: imgSrc});
let container = createRichElement('div', {style: containerStyle}, imgElem);

You can insert your container by replacing your insertAdjacentHTML with insertAdjacentElement.

The utility method gets even more practical when you have several elements in your “container”, possibly a mix of elements and text strings. F.ex:

let container = createRichElement('div', {style: containerStyle}, imgElem, " this is some text ", linkElem, " this is some more text ");

Well, at least I find it handy :slight_smile:

BTW, Now when we have a reviewer in the thread… @sylvaing you don’t happen to have an opinion on if use of iframes in extensions are considered using “remote scripts”? : Iframes in web extension popover?
I’m a little sad there newer was a response on that from someone who might now better than me and the poster of that question…

1 Like